一丶先引入上传下载的lib
二丶上传的的servlet
package com.test.action; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet("/upload") public class FileUpLoadAction extends HttpServlet { private static final long serialVersiOnUID= 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码 request.setCharacterEncoding("utf-8"); //对提交的数据进行处理,保存上传文件 boolean success = processUpload(request); if(success){ //获取表单text控件的值 String account = request.getAttribute("account").toString(); System.out.println(account); //获取文件上传的原始名称 String fileName = request.getAttribute("upfile").toString(); System.out.println(fileName); //获取文件上传后,服务器上保存的名字 String fileNameServer = request.getAttribute("upfileServer").toString(); System.out.println(fileNameServer); request.setAttribute("upfile", fileNameServer); request.setAttribute("message", "上传成功"); } request.getRequestDispatcher("/upload.jsp").forward(request, response); } private boolean processUpload(HttpServletRequest request) { boolean success = true; String message = null; // 获取文件需要上传到的路径 String path = request.getServletContext().getRealPath("/upload"); System.out.println(path); // 如果此文件夹不存在,则构造此文件夹 File f = new File(path); if (!f.exists()) { f.mkdir(); } // 构造出文件工厂,用于存放JSP页面中传递过来的文件 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置上传文件的保存路径 factory.setRepository(f); // 设置缓存大小,如果文件大于缓存大小时,则先把文件放到缓存中 factory.setSizeThreshold(1 * 1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); // 设置可以上传文件大小的上界20MB upload.setSizeMax(20 * 1024 * 1024); try { // 可以上传多个文件 Listlist = (List ) upload.parseRequest(request); for (FileItem item : list) { // 获取表单的属性名字 String name = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); //解决乱码问题 value = new String(value.getBytes("iso-8859-1"),"utf-8"); request.setAttribute(name, value); } else { // 获得文件类型 String cOntentType= item.getContentType(); // 获得文件大小 long fileSize = item.getSize(); // 获取路径名 String value = item.getName(); // 索引到最后一个反斜杠 int start = value.lastIndexOf("\\"); // 截取 上传文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start + 1); if (filename != null && !filename.trim().equals("")) { // 如果上传的文件不是图片,那么不上传 String allImgExt = ".jpg|.jpeg|.gif|.bmp|.png|"; String extName = filename.substring(filename.indexOf("."), filename.length()); if (allImgExt.indexOf(extName + "|") == -1) { message = "该文件类型不允许上传。请上传 " + allImgExt + " 类型的文件,当前文件类型为" + extName; success = false; break; } request.setAttribute(name, filename); // 随机数产生名称 String newName = System.currentTimeMillis() + extName; request.setAttribute(name + "Server", newName); // 将文件保存到服务器中 InputStream in = item.getInputStream(); // 原文件名 // OutputStream out = new FileOutputStream(new File(path, filename)); // 随机数文件名 OutputStream out = new FileOutputStream(new File(path, newName)); int length = 0; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } in.close(); out.close(); } } } } catch (FileUploadException e) { message = "文件的内容过大,请上传小于20MB的文件" ; success = false; e.printStackTrace(); } catch (IOException e) { success = false; e.printStackTrace(); } request.setAttribute("message", message); return success; } }
三丶下载的servlet
package com.test.action; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/download") public class FileDownloadAction extends HttpServlet { private static final long serialVersiOnUID= 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); // 根据主键读取文件的真实名字 + 服务器上的名字 processDownload("1444442288605.png", "腾讯.png", request, response); } private boolean processDownload(String fileName, String saveName, HttpServletRequest request, HttpServletResponse response) { boolean success = true; // 获取文件下载所在的路径 String path = request.getServletContext().getRealPath("/upload"); File fileLoad = new File(path, fileName); // 下载文件 long fileLength = fileLoad.length(); // 文件大小 byte[] buffer = new byte[1024]; // 缓冲字节数组 try { response.reset(); response.setHeader("Content-disposition", "attachment;filename=\"" + new String(saveName.getBytes("gb2312"), "ISO-8859-1") + "\""); response.setContentType("application/octet-stream"); response.setHeader("Content_Length", String.valueOf(fileLength)); OutputStream os = response.getOutputStream(); FileInputStream in = new FileInputStream(fileLoad); int hasRead = 0; while ((hasRead = in.read(buffer)) != -1) { os.write(buffer, 0, hasRead); } os.flush(); os.close(); in.close(); } catch (IOException e) { success = false; e.printStackTrace(); } return success; } }
以上所述是小编给大家介绍的JavaWeb中上传和下载文件实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!