上傳文件這個功能用的比較多,不難,可是每次寫都很彆扭。記錄在此,以備之後copy用。java
package com.**.**.**.web.api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; 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.FileOutputStream; import java.io.IOException; import java.net.URL; /** * @Author: zyydd * @Date: 2019/10/12 14:18 */ @RestController @RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class UploadController { private static final Logger logger = LoggerFactory.getLogger(UploadController.class); /** * 桶名,取配置 */ @Value("${jss.bucket}") private String bucket; private static String key = "file"; private static String springProperties = "application.properties"; @ResponseBody @RequestMapping(value = "/upload/{fileType}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ApiOperation(value = "文件上傳", notes = "文件上傳,form-data,key=file;fileType:pic、file", response = String.class, tags = {"UploadController",}) public String uploadFile(HttpServletRequest request, @PathVariable(value = "fileType") String fileType) { String result = ""; String fileAbsolutePath = ""; try { logger.info("uploadFile begin! fileType={}", fileType); //寫本地文檔 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartHttpServletRequest.getFile(key); String fileName = multipartFile.getOriginalFilename(); //文件名稱加隨機數處理,避免重名 fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() % 1000 + fileName.substring(fileName.lastIndexOf(".")); fileAbsolutePath = getUploadPath() + fileName; writeFile(fileAbsolutePath, multipartFile.getBytes()); //上傳各類雲的utils,返回一個上傳後可供下載的url,註解掉,按需處理。傳入本地文件的絕對路徑以及雲上桶名 String url = AmazonS3Utils.uploadFileToS3(fileAbsolutePath, bucket); if (StringUtils.isNotBlank(url)) { //持久化file數據到數據庫,返回數據ID,前臺頁面根據ID進行掛載,按需處理 Long fileId = fileService.insertFile(url, fileType); result = fileId + ""; } else { logger.error("上傳雲失敗,文件本地路徑={}", fileAbsolutePath); result = "上傳雲失敗"; } } catch (Exception e) { result = "上傳異常"; logger.error("uploadFile exception!", e); } finally { //上傳完成以後,確保刪除本地文件 try { if (StringUtils.isNotBlank(fileAbsolutePath)) { File f = new File(fileAbsolutePath); if (f.exists()) { f.delete(); } } } catch (Exception e) { logger.error("delete file exception", e); result = "刪除本地文件異常"; } logger.info("uploadFile end! result={}", result); return result; } } //經過spring的配置文件,來獲取war包的絕對路徑,並將文件上傳到預先準備的文件夾下 private String getUploadPath() { URL url = this.getClass().getClassLoader().getResource(springProperties); String uploadPath = url.getPath().replace(springProperties, "upload/"); return uploadPath; } public static void writeFile(String fileAbsolutePath, byte[] content) throws IOException { FileOutputStream fos = new FileOutputStream(fileAbsolutePath); fos.write(content); fos.close(); } }
相應的,postMan中,調用的示例截圖以下web