上傳到本地服務器下,不需要修改配置文件
在本地開發測試模式時,得到的地址為: {項目跟目錄}/target/static/images/upload/
在打包成jar發布到服務器上時,得到的地址為: {發布jar包目錄}/static/images/upload/
package cn.jiashubing.controller; import cn.jiashubing.common.StringConstants; import cn.jiashubing.result.ResultModel; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * @author jiashubing * @since 2019/6/25 */ @RestController @Api(tags = "稿件") @RequestMapping(value = StringConstants.API) public class ArticleController { @ApiOperation("上傳附件") @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public ResultModel<String> uploadFile(@RequestParam("file") @ApiParam(value = "二進制文件流") MultipartFile file) { String fileName = file.getOriginalFilename();//獲取文件名 fileName = getFileName(fileName); String filepath = getUploadPath(); if (!file.isEmpty()) { try (BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File(filepath + File.separator + fileName)))) { out.write(file.getBytes()); out.flush(); return new ResultModel<>(fileName); } catch (FileNotFoundException e) { return new ResultModel<>(false, "上傳文件失敗 FileNotFoundException:" + e.getMessage()); } catch (IOException e) { return new ResultModel<>(false, "上傳文件失敗 IOException:" + e.getMessage()); } } else { return new ResultModel<>(false, "上傳文件失敗,文件為空"); } } /** * 文件名后綴前添加一個時間戳 */ private String getFileName(String fileName) { int index = fileName.lastIndexOf("."); final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss"); //設置時間格式 String nowTimeStr = sDateFormate.format(new Date()); // 當前時間 fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index); return fileName; } /** * 獲取當前系統路徑 */ private String getUploadPath() { File path = null; try { path = new File(ResourceUtils.getURL("classpath:").getPath()); } catch (FileNotFoundException e) { e.printStackTrace(); } if (!path.exists()) path = new File(""); File upload = new File(path.getAbsolutePath(), "static/upload/"); if (!upload.exists()) upload.mkdirs(); return upload.getAbsolutePath(); } }
