• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java实现上传和下载功能(支持多个文件同时上传)

java 搞代码 4年前 (2022-01-05) 131次浏览 已收录 0个评论

这篇文章主要介绍了Java实现上传和下载功能,支持多个文件同时上传,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

文件上传一直是Web项目中必不可少的一项功能。

项目结构如下:(这是我之前创建的SSM整合的框架项目,在这上面添加文件上传与下载)

主要的是FileUploadController,doupload.jsp,up.jsp,springmvc.xml

1.先编写up.jsp

  <p>上传者:</p><p>选择文件:</p><p>选择文件:</p>

以上便是up.jsp的核心代码;

2.编写doupload.jsp

 <% request.setCharacterEncoding("utf-8"); String uploadFileName = ""; //上传的文件名 String fieldName = ""; //表单字段元素的name属性值 //请求信息中的内容是否是multipart类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //上传文件的存储路径(服务器文件系统上的绝对文件路径) String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" ); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { //解析form表单中所有文件 List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { //依次处理每个文件 FileItem item = (FileItem) iter.next(); if (item.isFormField()){ //普通表单字段 fieldName = item.getFieldName()<span style="color:transparent">来源gaodai#ma#com搞*代#码网</span>; //表单字段的name属性值 if (fieldName.equals("user")){ //输出表单字段的值 out.print(item.getString("UTF-8")+"上传了文件。<br />"); } }else{ //文件表单字段 String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); File saveFile = new File(uploadFilePath, fullFile.getName()); item.write(saveFile); uploadFileName = fullFile.getName(); out.print("上传成功后的文件名是:"+uploadFileName); out.print("\t\t下载链接:"+""+uploadFileName+""); out.print("<br />"); } } } } catch (Exception e) { e.printStackTrace(); } } %>

该页面主要是内容是,通过解析request,并设置上传路径,创建一个迭代器,先进行判空,再通过循环来实现多个文件的上传,再输出文件信息的同时打印文件下载路径。

效果图:

3.编写FilterController实现文件下载的功能(相对上传比较简单):

 @Controller public class FileUploadController { @RequestMapping(value="/download") public ResponseEntity download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception { //下载显示的文件名,解决中文名称乱码问题 filename=new String(filename.getBytes("iso-8859-1"),"UTF-8"); //下载文件路径 String path = request.getServletContext().getRealPath("/upload/"); File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); //下载显示的文件名,解决中文名称乱码问题 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8"); //通知浏览器以attachment(下载方式)打开图片 headers.setContentDispositionFormData("Content-Disposition", downloadFielName); //application/octet-stream : 二进制流数据(最常见的文件下载)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } }

4.实现上传文件的功能还需要在springmvc中配置bean:

  <!-- 上传文件大小上限,单位为字节(10MB) --> 10485760<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 --> UTF-8

完整代码如下:

up.jsp

   <title>File控件</title>  <p>上传者:</p><p>选择文件:</p><p>选择文件:</p>

doupload.jsp

   <title>上传处理页面</title> <% request.setCharacterEncoding("utf-8"); String uploadFileName = ""; //上传的文件名 String fieldName = ""; //表单字段元素的name属性值 //请求信息中的内容是否是multipart类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //上传文件的存储路径(服务器文件系统上的绝对文件路径) String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" ); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { //解析form表单中所有文件 List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { //依次处理每个文件 FileItem item = (FileItem) iter.next(); if (item.isFormField()){ //普通表单字段 fieldName = item.getFieldName(); //表单字段的name属性值 if (fieldName.equals("user")){ //输出表单字段的值 out.print(item.getString("UTF-8")+"上传了文件。<br />"); } }else{ //文件表单字段 String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); File saveFile = new File(uploadFilePath, fullFile.getName()); item.write(saveFile); uploadFileName = fullFile.getName(); out.print("上传成功后的文件名是:"+uploadFileName); out.print("\t\t下载链接:"+""+uploadFileName+""); out.print("<br />"); } } } } catch (Exception e) { e.printStackTrace(); } } %> 

FileUploadController.java

 package ssm.me.controller; import java.io.File; import java.net.URLDecoder; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.junit.runners.Parameterized.Parameter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { @RequestMapping(value="/download") public ResponseEntity download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception { //下载显示的文件名,解决中文名称乱码问题 filename=new String(filename.getBytes("iso-8859-1"),"UTF-8"); //下载文件路径 String path = request.getServletContext().getRealPath("/upload/"); File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); //下载显示的文件名,解决中文名称乱码问题 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8"); //通知浏览器以attachment(下载方式)打开图片 headers.setContentDispositionFormData("Content-Disposition", downloadFielName); //application/octet-stream : 二进制流数据(最常见的文件下载)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } }

SpringMVC.xml(仅供参考,有的地方不可以照搬)

   <!-- 一个用于自动配置注解的注解配置 --><!-- 扫描该包下面所有的Controller --><!-- 视图解析器 --> <!-- 上传文件大小上限,单位为字节(10MB) --> 10485760<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 --> UTF-8

web.xml(仅供参考,有的地方不可以照搬)

   Student index.htmlindex.htmindex.jspdefault.htmldefault.htmdefault.jsp springmvcorg.springframework.web.servlet.DispatcherServlet<!-- 初始化参数 --> contextConfigLocationclasspath:springmvc.xml1 springmvc*.action contextConfigLocationclasspath:spring/applicationContext-*.xml org.springframework.web.context.ContextLoaderListener

以上便为文件上传和下载的全部代码,博主亲测过,没有问题。

以上就是Java实现上传和下载功能(支持多个文件同时上传)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java实现上传和下载功能(支持多个文件同时上传)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址