JAVA 框架-Springmvc-文件上傳與下載
阿新 • • 發佈:2018-07-07
文件大小 list 文件 lookup location ng- see gettime 解析
需要的包: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.xsd 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-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屬性即可,僅支持火狐和谷歌瀏覽器--> <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\files
file.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;
@Controller
public 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-文件上傳與下載