
sPRingmvc文件上傳下載實現(xiàn)起來非常簡單,此springmvc上傳下載案例適合已經(jīng)搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架項目的搭建我相信你們已經(jīng)搭建好了,這里不再贅述,下面就開始吧!
ssm框架整合詳情請看:http://www.tpyyes.com/a/javaweb/2016/1103/23.html
1.首先我們創(chuàng)建一個測試用的jsp頁面,代碼如下。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>文件上傳下載</title></head><body> <form action="http://localhost:8080/uploadDemo/rest/file/upload" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="file" width="120px"> <input type="submit" value="上傳"> </form> <hr> <form action="http://localhost:8080/uploadDemo/rest/file/down" method="get"> <input type="submit" value="下載"> </form></body></html>2.在我們的maven項目的pom.xml文件中添加fileupload文件上傳下載jar包,不然后面的操作可能會報錯,如下。<!-- 文件上傳 --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3</version></dependency>3.在spring的servlet視圖解析器下面定義CommonsMultipartResolver文件解析器,就是加入這個的時候運行項目,如果沒有fileuload相關(guān)的jar包就會報錯。<!-- 定義文件解釋器 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 設(shè)置默認編碼 --> <property name="defaultEncoding" value="utf-8"></property> <!-- 上傳圖片最大大小5M--> <property name="maxUploadSize" value="5242440"></property> </bean>4.在controller層寫上springmvc上傳下載的代碼,如下。package com.baidu;@RequestMapping("file")@Controllerpublic class FileController { /** * 文件上傳功能 * @param file * @return * @throws IOException */ @RequestMapping(value="/upload",method=RequestMethod.POST) @ResponseBody public String upload(MultipartFile file,HttpServletRequest request) throws IOException{ String path = request.getsession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); File dir = new File(path,fileName); if(!dir.exists()){ dir.mkdirs(); } //MultipartFile自帶的解析方法 file.transferTo(dir); return "ok!"; } /** * 文件下載功能 * @param request * @param response * @throws Exception */ @RequestMapping("/down") public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{ //模擬文件,myfile.txt為需要下載的文件 String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt"; //獲取輸入流 InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //假如以中文名下載的話 String filename = "下載文件.txt"; //轉(zhuǎn)碼,免得文件名中文亂碼 filename = URLEncoder.encode(filename,"UTF-8"); //設(shè)置文件下載頭 response.addHeader("Content-Disposition", "attachment;filename=" + filename); //1.設(shè)置文件ContentType類型,這樣設(shè)置,會自動判斷下載文件類型 response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); }}springmvc上傳下載很方便,代碼直接復(fù)制使用。
新聞熱點
疑難解答