package com.cqyy.oa.web.controller; import com.cqyy.oa.common.base.BaseResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.UUID; @Api(tags = "上传下载文档") @RestController @RequestMapping("file") public class FileController { /** * 上传图片 * * @param file * @throws IOException */ @ApiOperation(value = "上传图片接口",notes = "上传图片") @RequestMapping(value = "upload", method = RequestMethod.POST) public BaseResponse upload(@RequestParam("file") MultipartFile file) throws IOException { String fileName = file.getOriginalFilename(); String name = fileName.substring(0,fileName.lastIndexOf(".")); /*String fileName = UUID.randomUUID().toString();*/ String ext = StringUtils.getFilenameExtension(file.getOriginalFilename()); if (StringUtils.isEmpty(ext)) { ext = "png"; } /* FTPUtils.uploadFile(name+"."+ext, "D:/file/"+name+"."+ext);*/ /*boolean flag = FTPUtils.downFile("ftp://172.16.3.16/hhl.png", "D:/file/hhl.png");*/ /*file.transferTo(new File("f://file/" + name + "." + ext));*/ BaseResponse baseResponse = new BaseResponse(); baseResponse.setMessage(name); return baseResponse; } /** * 文件流 * * @param response * @return */ @ApiOperation(value = "下载文件接口",notes = "下载文件") @RequestMapping(value = "stream/{fileName}/{ext}", method = RequestMethod.GET) public String thumbnail(HttpServletResponse response, @PathVariable("fileName") String fileName, @PathVariable("ext") String ext) { try { InputStream inputStream = new FileInputStream("f://file/" + fileName + "." + ext); OutputStream os = response.getOutputStream(); response.reset(); response.setContentType("bin"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName+ "." + ext + "\""); byte[] b = new byte[1024]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 这里主要关闭。 os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }