package com.example.swaggerDemo.controller.comoon;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
/**
* @Description
* @Author sgl
* @Date 2019-05-13 14:04
*/
@Api("文件上传接口")
@RestController
@RequestMapping(value="/Upload")
public class UploadController {
private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
@Autowired
private Environment env;
@ApiOperation(value="单文件上传",notes="单文件上传")
@ResponseBody
@RequestMapping(value= "/static/upload",method=RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
UUID uuid = UUID.randomUUID();
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
fileName =uuid+ "."+suffix;
String filePath =env.getProperty("upload.filePath");
File f = new File(filePath);
File fileParent = f.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
LOGGER.info("上传成功");
return "上传成功";
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
return "上传失败!";
}
@ApiOperation(value="多文件上传",notes="多文件上传")
@ResponseBody
@RequestMapping(value="/multiUpload",method=RequestMethod.POST)
public String multiUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
UUID uuid = UUID.randomUUID();
String filePath =env.getProperty("upload.filePath");
String fileName="";
File f = new File(filePath);
File fileParent = f.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);
if (file.isEmpty()) {
return "上传第" + (i++) + "个文件失败";
}
fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
fileName =uuid+ "."+suffix;
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
LOGGER.info("第" + (i + 1) + "个文件上传成功");
} catch (IOException e) {
LOGGER.error(e.toString(), e);
return "上传第" + (i++) + "个文件失败";
}
}
return "/upload/" + fileName;
}
}