重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
需要用到的流的相關(guān)知識(shí):https://www.jb51.net/article/170640.htm
創(chuàng)新互聯(lián)公司是專業(yè)的大化網(wǎng)站建設(shè)公司,大化接單;提供成都做網(wǎng)站、網(wǎng)站設(shè)計(jì),網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行大化網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
SpringMVC中寫好了文件上傳的類。
要使用文件上傳,首先需要文件上傳相關(guān)的Jar包。commons-fileupload.jar 和 commons-io.jar。
添加到pom.xml或lib文件夾下。
pom.xml:
commons-fileupload commons-fileupload 1.3.1 commons-io commons-io 2.4
在SprigMVC的配置文件中添加bean(id和class都是固定寫法):
前端寫一個(gè)單文件上傳的表單,一個(gè)多文件上傳的表單(多文件上傳的表單中,多個(gè)文件輸入input中的name相同):
文件上傳中,參數(shù)要使用MultipartFile而不是File類,不能使用FileUtils.copyFile()來復(fù)制文件,因此使用流來輸出到磁盤
單文件多文件只是將單文件中傳遞來的file參數(shù)改為數(shù)組形式,將方法內(nèi)的file有關(guān)的操作都變?yōu)閿?shù)組即可。
單文件上傳
也可以不使用流,下面這句看到有人使用,但是沒有測(cè)試。
File dest = new File(filePath + fileName); file.transferTo(dest);
@RequestMapping("testUpload") public String testUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException { System.out.println("文件描述:" + desc); // 得到文件的輸入流 InputStream inputStream = file.getInputStream(); // 得到文件的完整名字 img.png/hh.docx String fileName = file.getOriginalFilename(); // 輸出流 OutputStream outputStream = new FileOutputStream("C:\\tmp\\" + fileName); // 緩沖區(qū) byte[] bs = new byte[1024]; int len = -1; while ((len = inputStream.read(bs)) != -1) { outputStream.write(bs,0,len); } inputStream.close(); outputStream.close(); return "success"; }
多文件上傳
@RequestMapping("testMutiUpload") public String testMutiUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile[] files) throws IOException { System.out.println("文件描述:" + desc); for (MultipartFile file : files) { InputStream inputStream = file.getInputStream(); String fileName = file.getOriginalFilename(); OutputStream outputStream = new FileOutputStream("C:\\tmp\\" + fileName); byte[] bs = new byte[1024]; int len = -1; while ((len = inputStream.read(bs)) != -1) { outputStream.write(bs,0,len); } inputStream.close(); outputStream.close(); } return "success"; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。