一文件上传
文件上传主要分以下几个步骤:
(1)新建maven java project;
(2)在pom.xml加入相应依赖;
(3)新建一个文件上传表单页面;
(4)编写controller;
(5)测试;
(6)对上传的文件做一些限制;
(7)多文件上传实现
好了,直接看代码,代码中有详细注释
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wx</groupId>
<artifactId>springboot05</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jsp页面支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- jstl标签库 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 如果你不想用maven命令运行spring boot可以不用作此配置 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
页面文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="scheme" value="${pageContext.request.scheme}"></c:set>
<c:set var="serverName" value="${pageContext.request.serverName}"></c:set>
<c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${contextPath}/"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="${basePath}">
<title>文件上传下载</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$("[value=开始上传]").click(function(e){
var userName=$("[name=userName]").val();
if(userName==""){
window.alert("用户名不为空");
return;
}
var theFile=$("[name=theFile1]").val();
if(theFile==""){
window.alert("文件名不为空");
return;
}
var theSubfix=theFile.substr(theFile.lastIndexOf('.')+1);
theSubfix=theSubfix.toLowerCase();
window.alert("ttt:"+theSubfix);
var subfixs=["png","gif","jpg","jpeg","bmp"];
var flag=false;
for(var i=0;i<subfixs.length;i++){
if(subfixs[i]==theSubfix){
flag=true;
break;
}
}
if(!flag){
window.alert("文件格式错误!");
return;
}
$("[name=myFrm]").submit();
});
});
</script>
</head>
<body>
<h1>文件上传演示</h1>
<form action="Upload.php" name="myFrm" method="post" enctype="multipart/form-data">
<table border="1px">
<tr><td>请输入用户名:</td><td><input type="text" name="userName"/></td></tr>
<!-- 第一个文件限定为图片 -->
<tr><td>请选择文件:</td><td><input type="file" name="theFile1"/></td></tr>
<tr><td>请选择文件:</td><td><input type="file" name="theFile2"/></td></tr>
<tr><td colspan="2"><input type="button" value="开始上传"/></td></tr>
</table>
</form>
</body>
</html>
配置类
package com.wx.boot;
import java.nio.charset.Charset;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.StringHttpMessageConverter;
@Configuration
@ComponentScan(basePackages = "com.wx.controler.*")
public class SpringConfig {
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
return converter;
}
//统一错误处理配置
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
public void customize(ConfigurableEmbeddedServletContainer container) {
//ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/Err404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/Err500.html");
container.addErrorPages(error404Page,error500Page);
}
};
}
}
=启动类=====
文件上传控制器类
package com.wx.controler.user;
import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UploadController{
@RequestMapping(value="/Upload.php",method=RequestMethod.POST)
public ModelAndView login(HttpServletRequest request,
HttpServletResponse response) throws Exception{
String userName=request.getParameter("userName");
HttpSession session=request.getSession();
//获得文件请求对象
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
String targetPath=session.getServletContext().getRealPath("/")+"uploads\\";
System.out.println("path:"+targetPath+",userName:"+userName);
File targetDir=new File(targetPath);
if(!targetDir.exists()){
targetDir.mkdirs();
}
//键是文件表单的名称,值是文件对象
Map<String, MultipartFile> fileMap = mRequest.getFileMap();
Set<String> keys=fileMap.keySet();
FileOutputStream fos=null;
String srcName="";
List<String> nameList=new ArrayList<String>();
//对上传的文件进行处理,如果有多个文件表单则处理多次
for(String key : keys){
//原始文件名
srcName=fileMap.get(key).getOriginalFilename();
if(srcName==null || srcName.equals("")){
break;
}
nameList.add(srcName);
//获得输出流
fos=new FileOutputStream(targetPath+srcName);
//把输入流拷贝到输出流
FileCopyUtils.copy(fileMap.get(key).getInputStream(), fos);
}
request.setAttribute("userName", userName);
request.setAttribute("nameList", nameList);
return new ModelAndView("ShowFile");
}
}
上传好了的文件的展示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="scheme" value="${pageContext.request.scheme}"></c:set>
<c:set var="serverName" value="${pageContext.request.serverName}"></c:set>
<c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${contextPath}/"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="${basePath}">
<title>展示上传文件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<h2>上传人:${requestScope.userName }</h2>
<c:if test="${not empty requestScope.nameList}">
<c:forEach items="${requestScope.nameList}" var="oneName">
<h2>文件名:${oneName } <a href="Download.php?fileName=${oneName }">下载</a></h2>
</c:forEach>
</c:if>
</body>
</html>
二 文件下载
package com.wx.controler.user;
import java.io.FileInputStream;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DownloadControl {
@RequestMapping(value="/Download.php")
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception{
String fileName=request.getParameter("fileName");
//对a标签提交的文件名乱码处理
fileName=new String(fileName.getBytes("iso-8859-1"),"utf-8");
System.out.println("theName:"+fileName);
HttpSession session=request.getSession();
String filePath=session.getServletContext().getRealPath("/uploads")+"\\";
FileInputStream fis=new FileInputStream(filePath+fileName);
response.setContentType("application/x-msdownload");//表示以下载的方式回复客户请求
fileName=URLEncoder.encode(fileName, "utf-8"); //处理客户端附件的乱码问题
//设置是以附件的形式下载
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
//获得输出流,该输出流表示对客户端请求的反馈
ServletOutputStream sos=response.getOutputStream();
//拷贝输入流到输出流
FileCopyUtils.copy(fis, sos);
sos.close();
fis.close();
return null;
}
}