maven 项目 springMVC实现文件图片的上传下载功能详解(源码已提供,小白必看)
文件上傳是項(xiàng)目開發(fā)中最常見的功能之一 ,springMVC 可以很好的支持文件上傳,但是SpringMVC上下文中默認(rèn)沒有裝配MultipartResolver,因此默認(rèn)情況下其不能處理文件上傳工作。如果想使用Spring的文件上傳功能,則需要在上下文中配置MultipartResolver。
前端表單要求:為了能上傳文件,必須將表單的method設(shè)置為POST,并將enctype設(shè)置為multipart/form-data。只有在這樣的情況下,瀏覽器才會(huì)把用戶選擇的文件以二進(jìn)制數(shù)據(jù)發(fā)送給服務(wù)器;
<form action="" enctype="multipart/form-data" method="post"><input type="file" name="file"/><input type="submit"> </form>對(duì)表單中的 enctype 屬性做個(gè)詳細(xì)的說明:
application/x-www=form-urlencoded:默認(rèn)方式,只處理表單域中的 value 屬性值,采用這種編碼方式的表單會(huì)將表單域中的值處理成 URL 編碼方式。
multipart/form-data:這種編碼方式會(huì)以二進(jìn)制流的方式來處理表單數(shù)據(jù),這種編碼方式會(huì)把文件域指定文件的內(nèi)容也封裝到請(qǐng)求參數(shù)中,不會(huì)對(duì)字符編碼。
text/plain:除了把空格轉(zhuǎn)換為 “+” 號(hào)外,其他字符都不做編碼處理,這種方式適用直接通過表單發(fā)送郵件。
一旦設(shè)置了enctype為multipart/form-data,瀏覽器即會(huì)采用二進(jìn)制流的方式來處理表單數(shù)據(jù),而對(duì)于文件上傳的處理則涉及在服務(wù)器端解析原始的HTTP響應(yīng)。在2003年,Apache Software Foundation發(fā)布了開源的Commons FileUpload組件,其很快成為Servlet/JSP程序員上傳文件的最佳選擇。Servlet3.0規(guī)范已經(jīng)提供方法來處理文件上傳,但這種上傳需要在Servlet中完成。
而Spring MVC則提供了更簡(jiǎn)單的封裝。
Spring MVC為文件上傳提供了直接的支持,這種支持是用即插即用的MultipartResolver實(shí)現(xiàn)的。
Spring MVC使用Apache Commons FileUpload技術(shù)實(shí)現(xiàn)了一個(gè)MultipartResolver實(shí)現(xiàn)類:
CommonsMultipartResolver。因此,SpringMVC的文件上傳還需要依賴Apache Commons FileUpload的組件。
1、導(dǎo)入文件上傳的jar包,commons-fileupload , Maven會(huì)自動(dòng)幫我們導(dǎo)入他的依賴包 commons-io包;
2、配置bean:multipartResolver
【注意!!!這個(gè)bena的id必須為:multipartResolver , 否則上傳文件會(huì)報(bào)400的錯(cuò)誤!在這里栽過坑,教訓(xùn)!】
<!--文件上傳--> <dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version> </dependency> <!--servlet-api導(dǎo)入高版本的--> <dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version> </dependency> <!--文件上傳配置--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 --><property name="defaultEncoding" value="utf-8"/><!-- 上傳文件大小上限,單位為字節(jié)(10485760=10M) --><property name="maxUploadSize" value="10485760"/><property name="maxInMemorySize" value="40960"/></bean>
CommonsMultipartFile 的 常用方法:
String getOriginalFilename():獲取上傳文件的原名
InputStream getInputStream():獲取文件流
void transferTo(File dest):將上傳文件保存到一個(gè)目錄文件中
前端
<form action="/upload" enctype="multipart/form-data" method="post"><input type="file" name="file"/><input type="submit" value="upload"> </form>后端
@Controller public class FileController {//@RequestParam("file") 將name=file控件得到的文件封裝成CommonsMultipartFile 對(duì)象//批量上傳CommonsMultipartFile則為數(shù)組即可@RequestMapping("/upload")public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletResponse response, HttpServletRequest request) throws IOException {//上傳路徑保存設(shè)置String path=request.getServletContext().getRealPath("/upload");//獲取文件名 : file.getOriginalFilename();String uploadFileName = file.getOriginalFilename();//如果文件名為空,直接回到首頁!if ("".equals(uploadFileName)){return "redirect:/index.jsp";}System.out.println("上傳文件名 : "+uploadFileName);//如果路徑不存在,創(chuàng)建一個(gè)File realPath = new File("/upload");if (!realPath.exists()){realPath.mkdir();}System.out.println("上傳文件保存地址:"+realPath);InputStream is = file.getInputStream(); //文件輸入流OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件輸出流//讀取寫出int len=0;byte[] buffer = new byte[1024];while ((len=is.read(buffer))!=-1){os.write(buffer,0,len);os.flush();}os.close();is.close();return "redirect:/index.jsp";} }另一種方法
/* * 采用file.Transto 來保存上傳的文件 */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {//上傳路徑保存設(shè)置String path = request.getServletContext().getRealPath("/upload");File realPath = new File(path);if (!realPath.exists()){realPath.mkdir();}//上傳文件地址System.out.println("上傳文件保存地址:"+realPath);//通過CommonsMultipartFile的方法直接寫文件(注意這個(gè)時(shí)候)file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));return "redirect:/index.jsp"; }下載
@RequestMapping(value="/download") public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{//要下載的圖片地址String path = request.getServletContext().getRealPath("/upload");String fileName = "基礎(chǔ)語法.jpg";//1、設(shè)置response 響應(yīng)頭response.reset(); //設(shè)置頁面不緩存,清空bufferresponse.setCharacterEncoding("UTF-8"); //字符編碼response.setContentType("multipart/form-data"); //二進(jìn)制傳輸數(shù)據(jù)//設(shè)置響應(yīng)頭response.setHeader("Content-Disposition","attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));File file = new File(path,fileName);//2、 讀取文件--輸入流InputStream input=new FileInputStream(file);//3、 寫出文件--輸出流OutputStream out = response.getOutputStream();byte[] buff =new byte[1024];int index=0;//4、執(zhí)行 寫出操作while((index= input.read(buff))!= -1){out.write(buff, 0, index);out.flush();}out.close();input.close();return null; }總結(jié)
以上是生活随笔為你收集整理的maven 项目 springMVC实现文件图片的上传下载功能详解(源码已提供,小白必看)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP用Socket上传图片
- 下一篇: 嵌入式项目开发流程概述