java实现文件上传下载
更新时间:2018年08月30日 11:44:45 作者:DOLFAMINGO
这篇文章主要为大家详细介绍了java实现文件上传下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了java实现文件上传下载的具体代码,供大家参考,具体内容如下
一.上传
1.前端:
<form method="post" action="FileUpload" enctype="multipart/form-data"> <input type="file" name="uploadFile" /> <br/> <input type="submit" value="上传" /> </form>
2.后台:
import java.io.File; import java.io.IOException; import java.io.PrintWriter; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import dao.FileDao; @WebServlet("/FileUpload") public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; // 上传配置 private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB public FileUpload() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); if (!ServletFileUpload.isMultipartContent(request)) { // 如果不是则停止 out.println("Error: 表单必须包含 enctype=multipart/form-data"); out.flush(); return; } // 配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 factory.setSizeThreshold(MEMORY_THRESHOLD); // 设置临时存储目录 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE); // 中文处理 upload.setHeaderEncoding("UTF-8"); String uploadPath = request.getServletContext().getRealPath("/files"); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // 解析请求的内容提取文件数据 List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // 迭代表单数据 for (FileItem item : formItems) { // 处理不在表单中的字段 if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // 在控制台输出文件的上传路径 // System.out.println(filePath); // 保存文件到硬盘 if(storeFile.exists()) { out.println("上传失败,文件已存在!"); }else { item.write(storeFile); out.println("文件上传成功!"); } } } } } catch (Exception ex) { response.getWriter().println("文件上传成功!"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
二.下载
1.下载链接:
FileDownload?filename="+URLEncoder.encode(filename,"utf-8") --------- 需要对URL中的中文参数进行编码,否则会出现乱码
2.后台:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; 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("/FileDownload") public class FileDownload extends HttpServlet { private static final long serialVersionUID = 1L; public FileDownload() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String dirPath = request.getServletContext().getRealPath("/files"); String filename = URLEncoder.encode(request.getParameter("filename"),"utf-8"); //需要对URL中的中文参数进行编码,否则出现乱码 response.getWriter().println(filename); String filepath = dirPath + File.separator + filename; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); FileInputStream fileInputStream = new FileInputStream(filepath); int i = 0; while ((i = fileInputStream.read()) != -1) { out.write(i); } fileInputStream.close(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
使用SpringEvent解决WebUploader大文件上传解耦问题
Spring Event是Spring框架内建的一种发布/订阅模式的实现,它允许应用内部不同组件之间通过事件进行通信,本文以WebUploader大文件上传组件为例,在大文件处理的场景中使用SpringEvent的事件发布机制,灵活的扩展对文件的处理需求,需要的朋友可以参考下2024-07-07SpringBoot用JdbcTemplates访问Mysql实例代码
本篇文章主要介绍了SpringBoot用JdbcTemplates访问Mysql实例代码,非常具有实用价值,需要的朋友可以参考下2017-05-05JSON的String字符串与Java的List列表对象的相互转换
这篇文章主要介绍了JSON的String字符串与Java的List列表对象的相互转换,如果在浏览器端JSON是list则转为string结构来处理,需要的朋友可以参考下2016-04-04IDEA2023.3.4开启SpringBoot项目的热部署(图文)
本文使用的开发工具是idea,使用的是springboot框架开发的项目,配置热部署,可以提高开发效率,文中通过图文介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧2024-02-02
最新评论