您好,登錄后才能下訂單哦!
這篇“如何用SpringBoot框架來接收multipart/form-data文件”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“如何用SpringBoot框架來接收multipart/form-data文件”文章吧。
現(xiàn)在很多文件上傳類型都是multipart/form-data類型的,HTTP請(qǐng)求如下所示:
可是問題就在于如果用傳統(tǒng)的Struts2或者servlet等都可以很容易的實(shí)現(xiàn)文件接收的功能,例如下面的代碼就可以實(shí)現(xiàn):
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//判斷是否是表單文件類型 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); List items = sfu.parseRequest(request);//從request得到所有上傳域的列表 for(Iterator iter = items.iterator();iter.hasNext();){ FileItem fileitem =(FileItem) iter.next(); if(!fileitem.isFormField()&&fileitem!=null){//判讀不是普通表單域即是file System.out.println("name:"+fileitem.getName()); } }
可是今天我把這一段代碼放在SpringBoot上面的時(shí)候就怎么也接收不到文件信息了,一直以為是前端什么數(shù)據(jù)傳輸錯(cuò)了。后來才知道原來SpringBoot有它自己的接收請(qǐng)求的代碼。下面就給大家詳細(xì)介紹一下它是如何實(shí)現(xiàn)這個(gè)功能的。
首選做一個(gè)簡(jiǎn)單的案例,也就是單個(gè)文件上傳的案例。為了進(jìn)行這個(gè)案例,首先需要建立一個(gè)SpringBoot框架
前臺(tái)HTML代碼:
<html> <body> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="Upload"/> </form> </body> </html>
后臺(tái)接收代碼:
/** * 文件上傳具體實(shí)現(xiàn)方法; * * @param file * @return */ @RequestMapping("/upload") @ResponseBody public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { /* * 這段代碼執(zhí)行完畢之后,圖片上傳到了工程的跟路徑; 大家自己擴(kuò)散下思維,如果我們想把圖片上傳到 * d:/files大家是否能實(shí)現(xiàn)呢? 等等; * 這里只是簡(jiǎn)單一個(gè)例子,請(qǐng)自行參考,融入到實(shí)際中可能需要大家自己做一些思考,比如: 1、文件路徑; 2、文件名; * 3、文件格式; 4、文件大小的限制; */ BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File( file.getOriginalFilename()))); System.out.println(file.getName()); out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return "上傳失敗," + e.getMessage(); } catch (IOException e) { e.printStackTrace(); return "上傳失敗," + e.getMessage(); } return "上傳成功"; } else { return "上傳失敗,因?yàn)槲募强盏?"; } }
這樣便可以接收multipart/form-data類型的文件。接下來,我們來看一個(gè)上傳多個(gè)文件并且每個(gè)文件都有多個(gè)字段的案例。
前臺(tái)HTML界面:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <form method="POST" enctype="multipart/form-data" action="/batch/upload"> <p>文件1:<input type="text" name="id" /></p> <p>文件2:<input type="text" name="name" /></p> <p>文件3:<input type="file" name="file" /></p> <p><input type="submit" value="上傳" /></p> </form> </body> </html>
后臺(tái)接收代碼:
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(HttpServletRequest request) { MultipartHttpServletRequest params=((MultipartHttpServletRequest) request); List<MultipartFile> files = ((MultipartHttpServletRequest) request) .getFiles("file"); String name=params.getParameter("name"); System.out.println("name:"+name); String id=params.getParameter("id"); System.out.println("id:"+id); 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"; }
這樣就可以實(shí)現(xiàn)對(duì)多個(gè)文件的接收了功能了。
SpringBoot還可以對(duì)接收文件的格式還有個(gè)數(shù)等等進(jìn)行限制,我這里就不多說了,大家有興趣的可以自己去了解了解。
千萬要記住SpringBoot對(duì)multipart/form-data類型的文件接收和其它是不一樣的,大家以后遇到的時(shí)候要千萬小心,不要像我一樣一往無前的踩進(jìn)去還傻傻的以為是前端的錯(cuò)誤。
package cn.juhe.controller; import net.sf.json.JSONObject; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; @RestController public class UploadTest { /** * 接受未知參數(shù)名的多個(gè)文件或者一個(gè)文件 * * @param request 請(qǐng)求 * @return 返回 */ @PostMapping("/upload") public JSONObject handleFileUpload(HttpServletRequest request) { Iterator<String> fileNames = ((MultipartHttpServletRequest) request).getFileNames(); JSONObject result = null; while (fileNames.hasNext()) { String next = fileNames.next(); MultipartFile file = ((MultipartHttpServletRequest) request).getFile(next); System.out.println("file.getName():" + file.getName()); System.out.println("file.getOriginalFilename():" + file.getOriginalFilename()); String folder = "E:\\upload\\received\\"; String picName = new Date().getTime() + ".jpg"; File filelocal = new File(folder, picName); result = new JSONObject(); result.put(picName, folder + picName); try { file.transferTo(filelocal); } catch (IOException e) { e.printStackTrace(); } } JSONObject jsonObject = new JSONObject(); jsonObject.put("error_code", 223805); jsonObject.put("reason", "文件過大或上傳發(fā)生錯(cuò)誤"); Random random = new Random(); if (random.nextInt(10) > 3) { jsonObject.put("error_code", 0); jsonObject.put("reason", "success"); jsonObject.put("result", result); } return jsonObject; } /** * 知道參數(shù)名的文件上傳 * * @param multipartFile 文件 * @return 返回 * @throws IOException */ @PostMapping("/uploadCommon") //public JSONObject upload(MultipartFile multipartFile) throws IOException { public JSONObject upload(@RequestParam("A") MultipartFile multipartFile) throws IOException { String name = multipartFile.getName();//上傳文件的參數(shù)名 String originalFilename = multipartFile.getOriginalFilename();//上傳文件的文件路徑名 long size = multipartFile.getSize();//文件大小 String folder = "E:\\upload\\received\\"; String picName = new Date().getTime() + ".jpg"; File filelocal = new File(folder, picName); multipartFile.transferTo(filelocal); /* { "reason": "success", "result": { "D": "/upload/order/files/2016/a72750ad-8950-4949-b04a-37e69aff0d23.jpg", "A": "/upload/order/files/2016/6842811a-eb76-453b-a2f3-488e2bb4500e.jpg", "B": "/upload/order/files/2016/ccc96347-3cb8-4e2e-99a3-0c697b57eb88.jpg", "C": "/upload/order/files/2016/d470d533-a54b-406a-a0f9-bbf82c314755.jpg" }, "error_code": 0 }*/ JSONObject jsonObject = new JSONObject(); jsonObject.put("error_code", 223805); jsonObject.put("reason", "文件過大或上傳發(fā)生錯(cuò)誤"); Random random = new Random(); if (random.nextInt(10) > 3) { jsonObject.put("error_code", 0); jsonObject.put("reason", "success"); JSONObject result = new JSONObject(); result.put(name, folder + picName); jsonObject.put("result", result); } return jsonObject; } }
以上就是關(guān)于“如何用SpringBoot框架來接收multipart/form-data文件”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。