標籤:utf-8 array item workspace Fix iat sch download 標籤庫
需要的包:spring的21個包,commons-fileupload/io/logging的三個包,標準標籤庫2個包
異常處理:如果報BeanCreationException: Lookup method resolution failed 可能是缺少必須的包;
spring-servlet.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:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"><context:component-scan base-package="com.hanqi.controller"></context:component-scan><!--註解掃描器--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 視圖解析器 --><property name="prefix" value="/WEB-INF/page/"></property><property name="suffix" value=".jsp"></property></bean><!--配置spring裡帶的檔案上傳類--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 可以上傳的檔案的總大小, 單位(b), 1KB=1024b --><property name="maxUploadSize" value="1000000000"></property><!-- 可以上傳的單個檔案的大小, 單位(b) --><property name="maxUploadSizePerFile" value="100000000"></property><!-- 預設的字元集 --><property name="defaultEncoding" value="UTF-8"></property></bean></beans>
檔案上傳頁:
<%@ 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=UTF-8"><title>上傳檔案頁面</title></head><body><form action="file/upload.do" method="post" enctype="multipart/form-data"><input type="file" name="file" ><br><input type="submit" value="提交"></form><br><a href="${pageContext.request.contextPath }/download.do">查看上傳檔案</a></body></html>
檔案下載頁:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!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=UTF-8"><title>下載檔案頁面</title></head><body><a href="index.jsp">上傳檔案</a><br><!--第一種下載方式,直接加上download屬性即可,僅支援Firefox和Google瀏覽器--><c:forEach items="${fileList}" var="f"><a href="files/${f}" download>${f }</a><br></c:forEach><!--第二種下載方式,將檔案名稱作為請求參數傳入後台--><c:forEach items="${fileList}" var="f"><a href="file/download.do?filename=${f }">${f }</a><br></c:forEach></body></html>
檔案控制器類:
package com.hanqi.controller;import java.io.File;import java.io.IOException;import java.util.Date;import javax.servlet.http.HttpServletRequest;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.multipart.MultipartFile;@Controller@RequestMapping("/file")public class FileController {@RequestMapping("/upload")public String upload(MultipartFile file,HttpServletRequest request) {System.out.println(file.getName());// input控制項中name屬性的值System.out.println(file.getSize()); // 檔案大小System.out.println(file.getOriginalFilename());// 檔案名稱//在WebContent下建立一個files檔案夾,並擷取其實體路徑String path = request.getServletContext().getRealPath("/files");//建立一個空的檔案,File.separator相當於"/",同時加上一個時間戳記,用於區分相同名字的檔案File orgFile = new File(path + File.separator + new Date().getTime()+"-" + file.getOriginalFilename());try {//將已接收的檔案放到空的檔案中//該檔案實際存放在D:\eclipse workspace\.metadata\.plugins\org.eclipse.wst.server.core//\tmp0\wtpwebapps\spring-file\filesfile.transferTo(orgFile);} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return "success";}@RequestMapping("/download")public ResponseEntity<byte[]> testDownLoad(HttpServletRequest request,String filename) throws Exception {// String orgFilename = new String(filename.getBytes("iso-8859-1"), "utf-8");String path = request.getServletContext().getRealPath("/files");// File orgFile = new File(path + "/" + orgFilename);File orgFile = new File(path + "/" + filename);// 佈建要求頭資訊HttpHeaders hh = new HttpHeaders();// 告訴前台, 以(attachement, 就是下載)的方式開啟檔案hh.setContentDispositionFormData("attachment", new String(filename.getBytes("utf-8"), "iso-8859-1"));// 以二進位流的形式傳輸檔案, 這是最常見的下載方式hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(orgFile), hh, HttpStatus.CREATED);}}
頁面跳轉控制類:
package com.hanqi.controller;import java.io.File;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class FormController {@RequestMapping("/{path}")public String toPage(@PathVariable("path")String page,Model model,HttpServletRequest request) {if("download".equals(page)) {String path = request.getServletContext().getRealPath("/files");File orgFiles = new File(path);File[] files = orgFiles.listFiles();List fileList = new ArrayList();for(File f:files) {fileList.add(f.getName());}model.addAttribute("fileList", fileList);}return page;}}
JAVA 架構-Springmvc-檔案上傳與下載