导读


由于需要上传图片,这里列举了文件上传的步骤。

使用步骤


添加依赖

  1. <dependency>
  2. <groupId>commons-io</groupId>
  3. <artifactId>commons-io</artifactId>
  4. <version>2.6</version>
  5. </dependency>

修改配置文件application.yml

  1. spring:
  2. servlet:
  3. multipart:
  4. enabled: true
  5. max-file-size: 50MB
  6. max-request-size: 50MB

注:这里文件大小要大写的MB,如果是小写的Mb会报错。

或者修改对应的application.properties

  1. # 最大支持文件大小
  2. spring.servlet.multipart.max-file-size=50MB
  3. # 最大支持请求大小
  4. spring.servlet.multipart.max-request-size=50MB
  5. # 下方可加可不加
  6. #默认支持文件上传
  7. spring.servlet.multipart.enabled=true
  8. #支持文件写入磁盘.
  9. spring.servlet.multipart.file-size-threshold=0
  10. # 上传文件的临时目录
  11. spring.servlet.multipart.location=

定义一个model类

  1. import lombok.AllArgsConstructor;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import java.io.Serializable;
  5. /**
  6. * 处理后上传文件的信息
  7. */
  8. @Data
  9. @NoArgsConstructor
  10. @AllArgsConstructor
  11. public class UploadInfo implements Serializable {
  12. private static final long serialVersionUID = -2088268852466393733L;
  13. /**
  14. * 上传结果
  15. */
  16. private String result;
  17. /**
  18. * 初始文件名
  19. */
  20. private String beginFileName;
  21. /**
  22. * 最终上传文件名
  23. */
  24. private String lastFileName;
  25. /**
  26. * 文件类型
  27. */
  28. private String fileType;
  29. /**
  30. * 文件大小
  31. */
  32. private String fileSize;
  33. /**
  34. * 文件上传的地址
  35. */
  36. private String uploadUrl;
  37. }

创建Controller层

  1. import com.ck.model.UploadInfo;
  2. import com.ck.service.IndexService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import java.util.Map;
  12. @Controller
  13. @RequestMapping("/app")
  14. public class IndexController {
  15. @Autowired
  16. private IndexService uploadService;
  17. private final static String UPLOAD_FILE_PATH = "G:\\cksso\\resources\\upfile";
  18. /**
  19. *上传文件测试
  20. */
  21. @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  22. @ResponseBody
  23. public UploadInfo uploadTest(@RequestParam("file") MultipartFile file) {
  24. UploadInfo uploadInfo = null;
  25. try {
  26. uploadInfo = uploadService.upload(file, UPLOAD_FILE_PATH);
  27. } catch (Exception e) {
  28. System.out.println(e.toString());
  29. }
  30. return uploadInfo;
  31. }
  32. }

注:方法前需要加入注解@ResponseBody不然会出现_Error resolving template "xxx", template might not exist or might not be accessible by any of the configured Template Resolvers_错误。

创建Service定义接口

  1. import com.ck.model.UploadInfo;
  2. import org.springframework.web.multipart.MultipartFile;
  3. public interface IndexService {
  4. /**
  5. * 文件上传接口
  6. * @param file 文件名称
  7. * @param uploadFilePath 文件上传到服务器路径
  8. * @return
  9. * @throws Exception
  10. */
  11. UploadInfo upload(MultipartFile file, String uploadFilePath) throws Exception;
  12. }

创建Service实现层

  1. import com.ck.model.UploadInfo;
  2. import com.ck.service.IndexService;
  3. import org.springframework.stereotype.Service;
  4. import org.springframework.web.multipart.MultipartFile;
  5. import java.io.File;
  6. import java.util.UUID;
  7. @Service
  8. public class IndexServiceImpl implements IndexService {
  9. @Override
  10. public UploadInfo upload(MultipartFile file, String uploadFilePath) throws Exception {
  11. if (file.isEmpty()) {
  12. return null;
  13. }
  14. UploadInfo uploadInfo = new UploadInfo();
  15. String originalFilename;
  16. String fileName;
  17. originalFilename = file.getOriginalFilename();
  18. //为了防止上传的图片重复,这里使用UUID来处理
  19. fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
  20. String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
  21. long fileSize = file.getSize();
  22. File packageFile = new File(uploadFilePath);
  23. if (!packageFile.exists()) {
  24. packageFile.mkdir();
  25. }
  26. File targetFile = new File(uploadFilePath + "/" + fileName);
  27. //调用该方法实现文件上传
  28. file.transferTo(targetFile);
  29. uploadInfo.setBeginFileName(originalFilename);
  30. uploadInfo.setLastFileName(fileName);
  31. uploadInfo.setFileType(fileType);
  32. uploadInfo.setFileSize(Long.toString(fileSize));
  33. uploadInfo.setUploadUrl(targetFile.toString());
  34. uploadInfo.setResult("文件上传成功");
  35. return uploadInfo;
  36. }
  37. }

创建前台Thymeleaf页面

  1. <body>
  2. <form action="/app/uploadFile" method="POST" enctype="multipart/form-data">
  3. <input type="file" name="file"><br>
  4. <input type="submit" value="上传文件">
  5. </form>
  6. </body>

页面如下图所示:
image.png

结果测试

通过浏览器访问,在选择相应文件后点击上传,会出现以下响应结果,并且在项目的upfile文件夹能找到上传的文件,则表明成功上传。
image.png
项目中的upfile文件夹:
image.png

参考