<!-- 上傳下載須要設計到的jar包 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--servlet-api導入高版本的--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!-- 圖片處理類 --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>
# 上傳文件大小
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { ApplicationHome h = new ApplicationHome(getClass()); File jarF = h.getSource(); String dirPath = jarF.getParentFile().toString()+"/upload/"; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { //若是是Windows系統 registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath); } else { registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath); } } }
// 上傳文件 @ResponseBody @RequestMapping("/upload") public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException { // // win系統 上傳路徑保存設置 // // 獲取項目路徑 // File projectPath = new File(ResourceUtils.getURL("classpath:").getPath()); // // 絕對路徑=項目路徑+自定義路徑 // File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/"); // if (!pathFile.exists()) { // pathFile.mkdirs(); // } // //上傳文件地址 // UUID uuid = UUID.randomUUID(); // File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename()); // files.transferTo(serverFile); // // String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/"); // // return imgPath; // Linux服務器 上傳路徑保存設置 // 項目路徑 /home/www/ File pathFile = new File("/home/www/upload/"); if (!pathFile.exists()) { pathFile.mkdirs(); } //上傳文件地址 UUID uuid = UUID.randomUUID(); File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename()); files.transferTo(serverFile); String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/"); return imgPath; }
<form action="" class="layui-form" enctype="multipart/form-data" method="post"> <input type="hidden" name="blogImg" id="imgPath" value=""> <div class="form-group"> <label>圖片上傳</label> <input type='file' style='margin: 5px;' name='files' required><br> <button type="button" class="layui-btn" id="img_upload">上傳圖片</button> </div> <input type="submit"> </form>
//普通圖片上傳 $('#img_upload').click(function () { var formData = new FormData(); //獲取選擇的文件 $.each($('input[name="files"]'),function (index,item) { formData.append("files",item.files[0]) }); //發送異步請求 $.ajax({ method:'post', url: '[[@{/user/upload}]]', // 文件上傳接口 data:formData, processData: false, contentType:false, success:function (data) { //成功返回觸發的方法 $('#imgPath').val(data); alert("上傳成功"); }, //請求失敗觸發的方法 error:function () { alert("上傳失敗"); } }); });
@RequestMapping(value="/download") public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{ //要下載的圖片地址 String path = request.getServletContext().getRealPath("/upload"); String fileName = "基礎語法.jpg"; //一、設置response 響應頭 response.reset(); //設置頁面不緩存,清空buffer response.setCharacterEncoding("UTF-8"); //字符編碼 response.setContentType("multipart/form-data"); //二進制傳輸數據 //設置響應頭 response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //二、 讀取文件--輸入流 InputStream input=new FileInputStream(file); //三、 寫出文件--輸出流 OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //四、執行 寫出操做 while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return null; }
<a href="/download">點擊下載</a>
參考資料:狂神說SpringMVC:文件上傳下載java