关于项目中文件上传的两种方式-传统方式
概述场景
文件上传,是程序开发中必须会使用到一个功能,比如:
- 添加商品,用户头像,文章封面等需求
- 富文本编辑(插件文件上传)
文件上传原理是什么?
- 为什么要实现文件上传,就要共享资源,大家都可以看到你的在平台上上传的文件。简单来说你电脑上的文件上传到服务器上。
使用springboot如何实现文件上传呢?
-
使用springboot完成本地文件上传
步骤:
-
搭建一个springboot工程
-
准备一个页面文件上传的页面
在resouces/templates/upload.html
server: port: 8777 spring: freemarker: suffix: .html cache: false
-
实现后台的文件上传
定义文件上传的service
package com.taimi.springboot.service; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; /** * Description: * Author: taimi 37310 * Version: 1.0 * Create Date Time: 2021/12/15 21:51. * Update Date Time: * * @see */ @Service public class UploadService { /** * * @param multipartFile 底层自动会去和HttpServletRequest request中的request * .getInputStream()融合,从而达到文件上传的效果,也就是, * 文件上传底层原理是:request.getInputStream() * * @param dir * @return */ public String uploadImg(MultipartFile multipartFile,String dir){ //1.指定文件上传的目录 File targetFile = new File("D://tmptaimi/"+dir); try { if(!targetFile.exists()){ targetFile.mkdirs(); } File targetFileName = new File(targetFile, "shida.jpg"); multipartFile.transferTo(targetFileName); return "ok"; } catch (IOException e) { e.printStackTrace(); return "fail"; } } }
定制一个Controller
package com.taimi.springboot.controller; import com.taimi.springboot.service.UploadService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; /** * Description: * Author: taimi 37310 * Version: 1.0 * Create Date Time: 2021/12/15 21:58. * Update Date Time: * * @see */ @Controller public class UploadController { @Autowired private UploadService uploadService; /** * 实现上传具体实现 * @param multipartFile * @param request * @return */ @PostMapping("/upload/file") @ResponseBody public String upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){ if(multipartFile.isEmpty()){ return "文件有误!"; } //1: 获取用户指定的文件夹。为什么需要指定? //原因:做隔离 不同的文件放在不同的文件夹! String dir = request.getParameter("dir"); return uploadService.uploadImg(multipartFile,dir); } }
定制一个upload.html页面
<!
-