您现在的位置是:首页 > 个人日记个人日记

springMVC-07-文件上传

2019-02-14 18:20:03【个人日记】90人已围观

简介springMVC的文件上传,使用更加方便

文件上传

创建文件上传类

  1. package com.huangxin.order.controller;
  2. import com.huangxin.order.service.FileService;
  3. import com.huangxin.order.uploadUtil.R;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.*;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import java.io.File;
  9. import java.io.IOException;
  10. @Controller
  11. public class UploadController {
  12. @Autowired
  13. private FileService fileService;
  14. @GetMapping("/upload")
  15. public String upload() {
  16. return "upload/upload";
  17. }
  18. //单文件上传
  19. @PostMapping("/upload")
  20. @ResponseBody
  21. public R upload(MultipartFile multipartFile) {
  22. String str = fileService.upload(multipartFile);
  23. return R.ok(str);
  24. }
  25. //多文件上传
  26. @PostMapping("/uploads")
  27. @ResponseBody
  28. public R upload(@RequestParam("multipartFile") MultipartFile[] multipartFiles) {//多个文件上传
  29. try {
  30. for (MultipartFile multipartFile1 : multipartFiles) {
  31. File file = new File("D:/" + multipartFile1.getOriginalFilename());
  32. multipartFile1.transferTo(file);
  33. }
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. return R.error("文件上传失败");
  37. }
  38. return R.ok("文件上传成功");
  39. }
  40. }

工具类

  1. package com.huangxin.order.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.multipart.MultipartFile;
  4. import javax.servlet.http.HttpSession;
  5. import java.io.File;
  6. import java.io.IOException;
  7. public class FileService {
  8. @Autowired
  9. private HttpSession httpSession;
  10. public String upload(MultipartFile multipartFile) {
  11. String realPath = null;
  12. try {
  13. //拿到路径
  14. realPath = httpSession.getServletContext().getRealPath("/");
  15. File file = new File(realPath + multipartFile.getOriginalFilename());
  16. multipartFile.transferTo(file);//保存文件
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. return realPath;
  21. }
  22. }

Tags: JavaWeb  

评论区

    2019-05-27 22:39:38

    站长

    欢迎各位评论!


文章评论



给自个选个头像吧!






站点信息

  • 建站时间:   2019-01-31
  • 网站程序:   Tomcat+nginx
  • 文章统计:   44篇文章
  • 标签管理:   标签云
  • 微信公众号:  扫描二维码,联系我