springboot部署之后無法獲取項目目錄的問題:
之前看到網上有提問在開發一個springboot的項目時,在項目部署的時候遇到一個問題:就是我將項目導出為jar包,然后用java -jar 運行時,項目中文件上傳的功能無法正常運行,其中獲取到存放文件的目錄的絕對路徑的值為空,文件無法上傳。問題鏈接
不清楚此網友具體是怎么實現的,通常我們可以通過如下方案解決:
//獲取跟目錄 File path = new File(ResourceUtils.getURL("classpath:").getPath()); if(!path.exists()) path = new File(""); System.out.println("path:"+path.getAbsolutePath()); //如果上傳目錄為/static/images/upload/,則可以如下獲取: File upload = new File(path.getAbsolutePath(),"static/images/upload/"); if(!upload.exists()) upload.mkdirs(); System.out.println("upload url:"+upload.getAbsolutePath()); //在開發測試模式時,得到的地址為:{項目跟目錄}/target/static/images/upload/ //在打包成jar正式發布時,得到的地址為:{發布jar包目錄}/static/images/upload/
另外使用以上代碼需要注意,因為以jar包發布時,我們存儲的路徑是與jar包同級的static目錄,因此我們需要在jar包目錄的application.properties配置文件中設置靜態資源路徑,如下所示:
#設置靜態資源路徑,多個以逗號分隔 spring.resources.static-locations=classpath:static/,file:static/
以jar包發布springboot項目時,默認會先使用jar包跟目錄下的application.properties來作為項目配置文件。
具體項目實戰:
resttemplate上傳文件:
/**
* 處理文件上傳
*/
@RequestMapping("/remoteupload")
@ResponseBody
public String douploadRemote(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile) {
if (multipartFile.isEmpty()) {
return "file is empty.";
}
String originalFilename = multipartFile.getOriginalFilename();
String newFileName = UUIDHelper.uuid().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".") - 1);
File file = null;
try {
File path = new File(ResourceUtils.getURL("classpath:").getPath());
File upload = new File(path.getAbsolutePath(), "static/tmpupload/");
if (!upload.exists()) upload.mkdirs();
String uploadPath = upload + "\\";
file = new File(uploadPath + newFileName);
multipartFile.transferTo(file);
// 提交到另一個服務
FileSystemResource remoteFile = new FileSystemResource(file);
// package parameter.
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
multiValueMap.add("file", remoteFile);
String remoteaddr = "http://localhost:12345/test/doupload";
String res = restTemplate.postForObject(remoteaddr, multiValueMap, String.class);
return res;
} catch (Exception e) {
return "file upload error.";
} finally {
try{
file.delete();
} catch (Exception e) {
// nothing.
}
return "ok";
}
}
可以參見resttemplate文件上傳:
