SpringBoot中如何實(shí)現(xiàn)下載上傳?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
酒泉網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)公司2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。
最近在學(xué)習(xí)SpringBoot,以下是最近學(xué)習(xí)整理的實(shí)現(xiàn)文件上傳下載的Java代碼:
1、開發(fā)環(huán)境:
IDEA15+ Maven+JDK1.8
2、新建一個(gè)maven工程:
3、工程框架
4、pom.xml文件依賴項(xiàng)
4.0.0 SpringWebContent SpringWebContent war 1.0-SNAPSHOT SpringWebContent Maven Webapp http://maven.apache.org org.springframework.boot spring-boot-starter-parent 1.4.3.RELEASE org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-devtools true junit junit 3.8.1 test 1.8 SpringWebContent org.springframework.boot spring-boot-maven-plugin
5、Application.java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
6、FileController.java
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; @Controller public class FileController { @RequestMapping("/greeting") public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) { model.addAttribute("name", name); return "greeting"; } private static final Logger logger = LoggerFactory.getLogger(FileController.class); //文件上傳相關(guān)代碼 @RequestMapping(value = "upload") @ResponseBody public String upload(@RequestParam("test") MultipartFile file) { if (file.isEmpty()) { return "文件為空"; } // 獲取文件名 String fileName = file.getOriginalFilename(); logger.info("上傳的文件名為:" + fileName); // 獲取文件的后綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上傳的后綴名為:" + suffixName); // 文件上傳后的路徑 String filePath = "E://test//"; // 解決中文問題,liunx下中文路徑,圖片顯示問題 // fileName = UUID.randomUUID() + suffixName; File dest = new File(filePath + fileName); // 檢測(cè)是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上傳成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上傳失敗"; } //文件下載相關(guān)代碼 @RequestMapping("/download") public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){ String fileName = "FileUploadTests.java"; if (fileName != null) { //當(dāng)前是從該工程的WEB-INF//File//下獲取文件(該目錄可以在下面一行代碼配置)然后下載到C:\\users\\downloads即本機(jī)的默認(rèn)下載的目錄 String realPath = request.getServletContext().getRealPath( "http://WEB-INF//"); File file = new File(realPath, fileName); if (file.exists()) { response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設(shè)置文件名 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; } //多文件上傳 @RequestMapping(value = "/batch/upload", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(HttpServletRequest request) { Listfiles = ((MultipartHttpServletRequest) request) .getFiles("file"); MultipartFile file = null; BufferedOutputStream stream = null; for (int i = 0; i < files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); stream = new BufferedOutputStream(new FileOutputStream( new File(file.getOriginalFilename()))); stream.write(bytes); stream.close(); } catch (Exception e) { stream = null; return "You failed to upload " + i + " => " + e.getMessage(); } } else { return "You failed to upload " + i + " because the file was empty."; } } return "upload successful"; }
7、index.html
關(guān)于SpringBoot中如何實(shí)現(xiàn)下載上傳問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。