上传文件或图片 controller层

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class UploadController {

   private static final Logger log = LoggerFactory.getLogger(UploadController.class);

   @Autowired
   private FileUploadService uploadService;

   @RequestMapping("up")
   @ResponseBody
   public void up(@RequestParam MultipartFile file){

      // 1. uploadService.canupload  判断 能否保存文件

      // 2.

      uploadService.saveFile(FileTypeEnum.FILE_GUARANTEE,file,1L,1L);


   }

   @RequestMapping("/upload")
   @ResponseBody
   public JsonResult upload(DefaultMultipartHttpServletRequest multipartRequest, HttpServletRequest request) {
      JsonResult json = new JsonResult();
      json.setSuccess(true);
      if (multipartRequest != null) {
         Iterator iterator = multipartRequest.getFileNames();
         while (iterator.hasNext()) {
            MultipartFile file = multipartRequest.getFile((String) iterator.next());
            if (!file.isEmpty()) {
               log.debug("获取文件MIME类型-" + file.getContentType());// 获取文件MIME类型

               log.debug("获取表单中文件组件的名字-" + file.getName());// 获取表单中文件组件的名字

               log.debug("获取上传文件的原名-" + file.getOriginalFilename());// 获取上传文件的原名

               log.debug("获取文件的字节大小,单位byte-" + file.getSize());// 获取文件的字节大小,单位byte

               String fileName = UUID.randomUUID().toString().replaceAll("-", "")
                     + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 保存后的文件名
               log.info(fileName);

               try {
                  // 文件保存路径
                  String filePath = request.getServletContext().getRealPath("/") + "attached" + File.separator;
                  json.setMsg("上传成功,请查看【" + filePath + "】目录");
                  File uploadFile = new File(filePath + fileName);
                  uploadFile.mkdirs();
                  file.transferTo(uploadFile);// 保存到一个目标文件中。
                  Map, Object> m = new HashMap, Object>();
                  m.put("fileUrl", "/attached/" + fileName);
                  json.setObj(m);
               } catch (Exception e) {
                  json.setSuccess(false);
                  json.setMsg(e.getLocalizedMessage());
                  e.printStackTrace();
               }
            }
         }
      }
      return json;
   }

}

你可能感兴趣的:(Java)