FileController.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.example.cinema.controller;
  2. import com.example.cinema.vo.ResponseVO;
  3. import org.apache.commons.io.FileUtils;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.servlet.http.HttpSession;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.text.SimpleDateFormat;
  15. import java.util.Date;
  16. /**
  17. * @author fjj
  18. * @date 2019/3/12 5:11 PM
  19. */
  20. @RestController
  21. public class FileController {
  22. @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
  23. public ResponseVO upLoadFile(@RequestParam MultipartFile myFile, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
  24. String realFileName = "";
  25. if(myFile.isEmpty()) {
  26. return ResponseVO.buildFailure("图片未上传");
  27. }
  28. else {
  29. String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload")+File.separator;
  30. System.out.println(realPath);
  31. realFileName =new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + myFile.getOriginalFilename();
  32. String realFileAddress = realPath + realFileName;
  33. System.out.println(realFileAddress);
  34. FileUtils.copyInputStreamToFile(myFile.getInputStream(), new File(realFileAddress));
  35. }
  36. return ResponseVO.buildSuccess("/uploads/" + realFileName);
  37. }
  38. }