江帅帅:精通 Spring Boot 系列 06
Spring Boot 文件的上传下载
说真的,在 Spring Boot 实现文件下载,真的是方便到让我颤抖。Java 中实现文件上传可以用两个组件:CommonMultipartResolver 和 StandardServletMultipartResolver。
Spring Boot 在 web 模块中集成了 Spring MVC ,文件上传这块儿的支持是可以通过即插即用的 MultipartResolver 实现类:CommonMultipartResolver。如果用它,则需要使用 commons-fileupload 组件来处理。
Spring Boot 提供的文件上传自动化配置类是 MultipartAutoConfiguration 中默认使用了 StandardServletMultipartResolver,在上传文件甚至能够做到零配置。
1. 单文件上传1)添加 fileUpload.html 文件在上传页面的表单中,添加一个 type 为 file 的控件,用来选择需要上传的图片文件。上传的接口是“/upload”,另外 method 要设置为“post”,还有 enctype 要设置为“multipart/form-data”,代码具体如下:
upload2)添加 FileUploadController 文件
首先,设置我们的文件上传路径为项目运行目录下的 upload 文件夹。然后,我们用 MultipartFile 来绑定上传的文件,使用 transferTo() 方法可以非常方便实现文件存储到磁盘当中。具体实现代码如下:
(){Stringpath=req.getSession().getServletContext().getRealPath();Filefolder=File(path);(!folder.isDirectory()){folder.mkdirs();}StringoName=uploadFile.getOriginalFilename();StringnName=UUID.randomUUID().toString()+oName.substring(oName.lastIndexOf(),oName.length());{uploadFile.transferTo(File(folder+File.separator+nName));StringfilePath=req.getScheme()++req.getServerName()++req.getServerPort()++nName;;}(IOExceptionex){ex.printStackTrace();};}
地址栏中,输入 http://localhost:8080/fileUpload.html 选择文件上传,具体运行效果如下:
2. 采用对象方式来上传文件很多时候的上传操作,也都会把文件作为对象的属性进行保存,具体如何实现?下面通过注册页面,填写用户的相关信息,然后点击注册来上传 User 对象。
1)添加 fileUpload2.html 文件通过一个表单,来收集用户的具体信息,然后点击“注册用户”按钮即可提交 /register 注册请求。代码具体如下:
用户名:密码:头像:2)添加 User 类
User 类主要是用来封装用户信息的,其中 MultipartFile 类型的 pic 是用来接收上传的图像文件。
{Stringusername;Stringpassword;MultipartFilepic;}3)添加 userRegister() 方法
在 userRegister() 方法形参列表中,使用 @ModelAttribute 注解将表单提交的数据绑定到 User 对象中,其中图片会保存到 User 的 pic 属性中,然后转换为 Multipart 类型。文件上传成功之后,所有的用户信息都保存到 model 当中。
{(){(!user.getPic().isEmpty()){StringpicPath=req.getServletContext().getRealPath();StringpicName=user.getPic().getOriginalFilename();FilefilePath=File(picPath,picName);(!filePath.getParentFile().exists()){filePath.getParentFile().mkdirs();}user.getPic().transferTo(File(picPath+File.separator+picName));model.addAttribute(,user);;}{;}}}
3)在 templates 目录中,添加 userMsg.html 文件
用户名
运行效果,具体如下:
选第一张图片:选第二张图片:选第三张图片:2)添加 uploadFiles() 方法
(){Stringpath=req.getSession().getServletContext().getRealPath();Filefolder=File(path);(!folder.isDirectory()){folder.mkdirs();}(!=uploadFiles&&uploadFiles.length>){(MultipartFileuploadFile:uploadFiles){StringoName=uploadFile.getOriginalFilename();StringnName=UUID.randomUUID().toString()+oName.substring(oName.lastIndexOf(),oName.length());{uploadFile.transferTo(File(folder,nName));;}(IOExceptionex){ex.printStackTrace();}}};}
运行结果,具体如下:
用户名下载头像2)添加 downloadPic() 方法
这里使用了 ResponseEntity 类型,就能定义返回的 HttpHeaders、BodyBuilder 和 HttpStatus,然后返回客户端下载。
(value=)ResponseEntity<[]>downloadPic(HttpServletRequestrequest,()Stringfilename,()StringuserAgent,Modelmodel)Exception{Stringpath=request.getServletContext().getRealPath();Filefile=File(path+File.separator+filename);BodyBuilderbuilder=ResponseEntity.ok();builder.contentLength(file.length());builder.contentType(MediaType.APPLICATION_OCTET_STREAM);filename=URLEncoder.encode(filename,);(userAgent.indexOf()>){builder.header(,+filename);}{builder.header(,+filename);}builder.body(FileUtils.readFileToByteArray(file));}
运行效果,具体如下:
免费领取更多技术资料及视频
本文来源于:奈学开发者社区-江帅帅
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。