① jsp+servlet实现文件上传与下载源码
上传:需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jarimport java.io.File;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * 上传附件 * @author new * */public class UploadAnnexServlet extends HttpServlet { private static String path = ""; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /* * post处理 * (non-Javadoc) * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { path = this.getServletContext().getRealPath("/upload"); try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload up = new ServletFileUpload(factory); List<FileItem> ls = up.parseRequest(request); for (FileItem fileItem : ls) { if (fileItem.isFormField()) { String FieldName = fileItem.getFieldName(); //getName()返回的是文件名字 普通域没有文件 返回NULL // String Name = fileItem.getName(); String Content = fileItem.getString("gbk"); request.setAttribute(FieldName, Content); } else { String nm = fileItem.getName().substring( fileItem.getName().lastIndexOf("\\") + 1); File mkr = new File(path, nm); if (mkr.createNewFile()) { fileItem.write(mkr);//非常方便的方法 } request.setAttribute("result", "上传文件成功!"); } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("result", "上传失败,请查找原因,重新再试!"); } request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward( request, response); }} 下载(i/o流)无需导包:import java.io.IOException;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 下载文件 * @author * */public class DownloadFilesServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 8594448765428224944L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /* * 处理请求 * (non-Javadoc) * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("fileName"); System.out.print("dddddddddd:" + name); // web绝对路径 String path = request.getSession().getServletContext().getRealPath("/"); String savePath = path + "upload"; // 设置为下载application/x-download response.setContentType("application/x-download"); // 即将下载的文件在服务器上的绝对路径 String filenamedownload = savePath + "/" + name; // 下载文件时显示的文件保存名称 String filenamedisplay = name; // 中文编码转换 filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay); try { java.io.OutputStream os = response.getOutputStream(); java.io.FileInputStream fis = new java.io.FileInputStream( filenamedownload); byte[] b = new byte[1024]; int i = 0; while ((i = fis.read(b)) > 0) { os.write(b, 0, i); } fis.close(); os.flush(); os.close(); } catch (Exception e) { } }}
② 怎么用servlet上传文件到该WEB项目的WebRoot的某文件夹下啊是相对路径不是绝对路径,请问怎么做啊
这个问题我以前也有过,但后来我明白了,虽然说JSP能编译为Servlet但是,这只是web容器的功劳。你要是边几个项目就会明白。好的WEB程序里。JSP和HTML文件的编写是一样的。除了一些必要的处理代码块。但是很少有。一般处理请求的都放在了servlet里,现在Struts很好的封装了Servlet这一层,成为了servelt的专业框架。用来处理用户的请求。但有必要的时候,我们还必须自己去写Servlet,比如过滤器,再比如监听器等。所以说,虽然JSP能编译为Servlet但并不代表他就能替代Servlet。一般的web项目尽量将显示代码放进jsp中而处理代码放进Servlet中。以增加可读性,可拓展性。可维护性。可能我说的有点深奥,但是你以后去做项目时就会明白了。JSP是绝不能替代Servlet的。希望对你有帮助。
③ java如何将导出的excel下载到客户端
packagecom.mr;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.ServletOutputStream;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/***利用Servlet导出Excel*@N**/{publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("UTF-8");//设置request的编码方式,防止中文乱码StringfileName="导出数据";//设置导出的文件名称StringBuffersb=newStringBuffer(request.getParameter("tableInfo"));//将表格信息放入内存StringcontentType="application/vnd.ms-excel";//定义导出文件的格式的字符串StringrecommendedName=newString(fileName.getBytes(),"iso_8859_1");//设置文件名称的编码格式response.setContentType(contentType);//设置导出文件格式response.setHeader("Content-Disposition","attachment;filename="+recommendedName+""");//response.resetBuffer();//利用输出输入流导出文件ServletOutputStreamsos=response.getOutputStream();sos.write(sb.toString().getBytes());sos.flush();sos.close();}}<%@pagelanguage="java"contentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"><title>导出Excel</title><scripttype="text/javascript">functiontest(){document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;}</script><style>body{font-family:宋体;font-size:11pt}</style></head><body><formaction="<%=request.getContextPath()%>/servlet/ExportExcelServlet"method="post"><spanid="table"><tablebgcolor="#EEECF2"bordercolor="#A3B2CC"border="1"cellspacing="0"><tr><th>学号</th><th>姓名</th><th>科目</th><th>分数</th></tr><tr><td>10001</td><td>赵二</td><td>高数</td><td>82</td></tr><tr><td>10002</td><td>张三</td><td>高数</td><td>94</td></tr><tr><td>10001</td><td>赵二</td><td>线数</td><td>77</td></tr><tr><td>10002</td><td>张三</td><td>线数</td><td>61</td></tr></table></span><br/><inputtype="submit"name="Excel"value="导出表格"onclick="test()"/><inputtype="hidden"id="tableInfo"name="tableInfo"value=""/></form></body></html>
以上代码来自网络:http://jtlyuan.iteye.com/blog/1322097
④ java:servlet接收图片,并把它保存到数据库中
这种代码网上不是一大片吗
publicbooleanstoreImage(Filefile){try{//打开文件FileInputStreamfin=newFileInputStream(file);//建一个缓冲保存数据ByteBuffernbf=ByteBuffer.allocate((int)file.length());byte[]array=newbyte[1024];intoffset=0,length=0;//读存数据while((length=fin.read(array))>0){if(length!=1024)nbf.put(array,0,length);elsenbf.put(array);offset+=length;}//关闭文件fin.close();//新建一个数组保存要写的内容byte[]content=nbf.array();Stringsql="insertintoimages(bin_data)values(?)";PreparedStatementpstmt=conn.prepareStatement(sql);pstmt.setBytes(1,content);pstmt.execute();pstmt.close();}catch(Exceptione){e.printStackTrace();returnfalse;}returntrue;}
⑤ java jsp中如何实现下载.csv文件、并自动保存到指定的文件夹下
你这种想法来不太现实首先你客户端自要跟服务器交互是要客户端主动发送请求然后建立连接去操作就算你不手动选保存路径,那你还是要写代码去实现这个过程的实现方式就两种了bs跟cs架构均可思路是一样的BS:servlet读取本地文件,然后以流的形式输出就行,注意要设置输出的MINE类型也就是contentType 你客户端写个程序通过http访问这个servlet,然后通过程序去保存到你移动硬盘 如果是cs架构的话,你的服务端监听socket如果有客户端连接那就等待接收命令或者是直接往客户端传文件的二进制流客户端:已启动就连接服务端,发送文件请求,处理回传的文件字节流