檔案上傳(StringMVC)

來源:互聯網
上載者:User

標籤:介紹   pat   list   log   適配   dispatch   ase   註解   nload   

我們經常會使用的一個功能是檔案下載,既然有檔案下載就會有檔案上傳,下面我們來看一下檔案上傳是如何?的

首先準備好一個頁面

jsp

<style type="text/css">        form{            margin:0px auto;             border:1px solid red;            width:500px;            padding:20px;        }    </style>  </head>    <body>   <form action="${pageContext.request.contextPath }/frist.do" method="post" enctype="multipart/form-data">       <h1>檔案上傳</h1>       檔案:<input type="file" name="uploadFile"/><br/>       檔案:<input type="file" name="uploadFile"/><br/>       檔案:<input type="file" name="uploadFile"/><br/>       <input type="submit" value="上傳">   </form>  </body>

單檔案上傳 

通過對檔案的大小來判斷是否有檔案

通過檔案的類型來判斷是否是允許

@Controllerpublic class MyController {@RequestMapping(value="/frist.do", method=RequestMethod.POST)public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{if(uploadFile.getSize()>0){//02.擷取前半部分路徑,jiangWebRoot下一個名稱為images檔案夾  轉換成絕對路徑String path = session.getServletContext().getRealPath("/upload");//01.擷取檔案名稱作為儲存到伺服器的檔案名稱String fileName=uploadFile.getOriginalFilename();if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){//03.路徑拼接File file = new File(path,fileName);uploadFile.transferTo(file);}return "welcome.jsp";}return "error.jsp";}

 applicationContext.xml配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd        "><!-- 配置包掃描器 --><context:component-scan base-package="cn.controller"></context:component-scan><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><!-- 用戶端發送資料的編碼 --><property name="maxUploadSize" value="5242880"></property><!-- 上傳檔案的大小 --><!-- <property name="uploadTempDir" value="/upload"></property> --></bean><!-- mvc註解驅動 --><mvc:annotation-driven /></beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>  <!-- ================spring mvc 適配器================ -->    <servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:applicationContext.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>springmvc</servlet-name>    <url-pattern>*.do</url-pattern>  </servlet-mapping> <!-- ================================================== -->      <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

  

 

多檔案上傳(多檔案上傳與單檔案上傳配置相同下面介紹一下不同的地方)

標記為紅色的欄位為多檔案上傳 與單檔案上傳的區別

     @RequestMapping(value="/firstdown.do")public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session)throws Exception{for (MultipartFile item : uploadFile) {if(item.getSize()>0){//02.擷取前半部分路徑,jiangWebRoot下一個名稱為images檔案夾  轉換成絕對路徑String path = session.getServletContext().getRealPath("/upload");//01.擷取檔案名稱作為儲存到伺服器的檔案名稱String fileName=item.getOriginalFilename();if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){//03.路徑拼接File file = new File(path,fileName);item.transferTo(file);}return "welcome.jsp";}}return "error.jsp";}

檔案下載

@RequestMapping(value="/first.do")

public static void download(HttpServletRequest request, HttpServletResponse response, String storeName, String contentType ) throws Exception { request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; //擷取項目根目錄 String ctxPath = request.getSession().getServletContext() .getRealPath(""); //擷取下載檔案露肩 String downLoadPath = ctxPath+"/uploadFile/"+ storeName; //擷取檔案的長度 long fileLength = new File(downLoadPath).length(); //設定檔案輸出類型 response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment; filename=" + new String(storeName.getBytes("utf-8"), "ISO8859-1")); //設定輸出長度 response.setHeader("Content-Length", String.valueOf(fileLength)); //擷取輸入資料流 bis = new BufferedInputStream(new FileInputStream(downLoadPath)); //輸出資料流 bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } //關閉流 bis.close(); bos.close(); }

下載直接存取控制器如:http:\\localhost:8080/springmvc/download.do

 或者通過JSP頁面

<a href="./downloadFile/download" >下載</a>  

  

 

檔案上傳(StringMVC)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.