springboot項目部署比較容易,打個jar包就可以了,但是這樣導致其上傳文件的位置不穩定,
網上找了好多例子,都是指定絕對文件夾進行上傳的,最后為了項目需求照貓畫虎弄了一個
- 先看前端
<img id="upload" src="/img/webuploader.png" title="公司logo" style="width: 80px; height: 80px; margin: 10px 0px;border-radius:50%;" /> <h6 style="color:#333;"><font class="x-form-item star">*</font>(注:圖片僅支持jpg、png、gif格式,大小不超過1M)</h6> <input id="companyLogo" name="companyLogo" style="position: absolute;width:80px; top: 10px; bottom: 50px; left: 45%;right: 0; opacity: 0;" type="file" enctype="multipart/form-data" accept=".gif, .jpg, .png" onchange="showImg(this)"/>
- js文件
var formData = new FormData();
formData.append('companyLogo', $('#companyLogo')[0].files[0]); //添加圖片信息的參數
- controller接收
public KZResult add(@RequestParam(value = "companyLogo", required = false)MultipartFile companyLogo, @RequestParam Map<String,String> map )
- 圖片上傳工具類
/** * SpringBoot上傳文件工具類 * @author lyy */ public class FileUtil { /** 絕對路徑 **/ private static String absolutePath = ""; /** 靜態目錄 **/ private static String staticDir = "static"; /** 文件存放的目錄 **/ private static String fileDir = "/img"; /** * 上傳單個文件 * 最后文件存放路徑為:static/img/11.jpg * 文件訪問路徑為:http://127.0.0.1:8080/img/11.jpg * 該方法返回值為:/img/11.jpg * @param inputStream 文件流 * @param path 文件路徑,如:image/ * @param filename 文件名,如:test.jpg * @return 成功:上傳后的文件訪問路徑,失敗返回:null */ public static String upload(InputStream inputStream, String path, String filename) { //第一次會創建文件夾 createDirIfNotExists(); String resultPath = fileDir + path + filename; //存文件 File uploadFile = new File(absolutePath, staticDir + resultPath); try { FileUtils.copyInputStreamToFile(inputStream, uploadFile); } catch (IOException e) { e.printStackTrace(); return null; } return resultPath; } /** * 創建文件夾路徑 */ private static void createDirIfNotExists() { if (!absolutePath.isEmpty()) {return;} //獲取跟目錄 File file = null; try { file = new File(ResourceUtils.getURL("classpath:").getPath()); } catch (FileNotFoundException e) { throw new RuntimeException("獲取根目錄失敗,無法創建上傳目錄!"); } if(!file.exists()) { file = new File(""); } absolutePath = file.getAbsolutePath(); File upload = new File(absolutePath, staticDir + fileDir); if(!upload.exists()) { upload.mkdirs(); } } /** * 刪除文件 * @param path 文件訪問的路徑upload開始 如:img/11.jpg * @return true 刪除成功; false 刪除失敗 */ public static boolean delete(String path) { File file = new File(absolutePath, staticDir + path); if (file.exists()) { return file.delete(); } return false; } }
- 文件上傳service
public class FileSercive { public String editMovieInfo(MultipartFile file,String uploadDir,String str) { try { //上傳 String s=file.getOriginalFilename(); //獲取文件名 String suffix[]=s.split("\\."); //獲取文件后綴名 String filename =str+"."+suffix[suffix.length-1]; //文件重新命名 String path=FileUtil.upload(file.getInputStream(), uploadDir,filename ); //文件上傳后的目錄 return path; } catch (Exception e){ return null; } } }