一、下載一個E盤存在jpg文件 java
【1】由於是spring-mvc 並且是文件上傳 ,因此須要導入如下包(可能會有多餘,可是絕對夠用),核心jar包是(commons-io和commons-fileupload)web
【2】編寫大配置文件applicationContext.xmlspring
<context:component-scan base-package="cn.happy.test"></context:component-scan>apache
【3】編寫上傳文件類spring-mvc
package cn.happy.test; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpSession; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUp { @RequestMapping("/download.do") public ResponseEntity<byte[]> download(String filename) throws IOException { HttpHeaders headers = new HttpHeaders(); String file="E:\\"+filename; File file2 = new File(file); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); System.out.println(filename); String charset=new String(filename.getBytes("utf-8"),"iso-8859-1"); headers.setContentDispositionFormData("file", charset); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file2), headers, HttpStatus.CREATED); } }
在前臺寫一個a標籤mvc
<a href="${pageContext.request.contextPath }/download.do?filename=呵呵.jpg">下載</a>app
web.xml配置編碼
<!--編碼過濾器 --> <filter> <filter-name>characterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置中英調度器 --> <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>
直接拷貝就行url