1. firstly 我们需要准备好两个包 分别为 commons-io-1.3.2.jar 以及 commons-fileupload-1.2.1.jar
2. 我们要明确实施的方式
Web页面使用file标签上传一个文件 以form标签来包装 再通过servlet的方式将form数据转发到后台Servlet
后台Servlet通过request获取到form的数据之后 找到真实文件 指定服务器端的一个路径 然后将真实文件以流的方式写入到指定路径下
掉转到原上传页面将路径以参数的形式传递到上传页面上
上传页面根据给定的路径来加载相关的文件
3.具体的代码文件
首先是jsp,index.jsp
注意这里的<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>避免页面中文乱码
还有<%request.setCharacterEncoding("UTF-8");%> 保证request解析到的中文不会乱码
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" target="_blank" rel="external nofollow" >
<title>My JSP 'index.jsp' starting page</title>
<script type='text/javascript' src='/FileUploadDownLoad/jquery-2.1.1.js'></script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" target="_blank" rel="external nofollow" >
-->
<script type='text/javascript'>
function download() {
alert("down load the file");
<%request.setCharacterEncoding("UTF-8");%>
location.href = "<%=request.getScheme() +"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath() + "/"+request.getParameter("fileName")%>";
}
</script>
</head>
<body>
<h>With this page, you can upload your file. </h>
<br>
<form action="upload" method="post" enctype="multipart/form-data">
username : <input type="text" name="username"><br/>
<input type="file" name="myfile">
<input type="submit" value="submit">
</form>
<input type="button" value="downLoad" onClick = "download();">
</body>
</html>
第二部分web,xml 用来对servlet前后台交互的设置
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FileUploadDownLoad</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.java.servlet.UploadHandleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>
第三部分 Servlet类 UploadHandleServlet
package com.java.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
* @author zero
*
*/
public class UploadHandleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("get the request from the page....");
String path = req.getRealPath("/upload");//create a path to save the file uploaded
System.out.println(path);
File file = new File(path);
file.mkdirs();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(file); //set temporary file
factory.setSizeThreshold(1024*1024);//set temporary file's size
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");//set the encoding language
try {
List<FileItem> list = (List<FileItem>)upload.parseRequest(req); //get the item list from the from label
for(FileItem item : list) {
String name = item.getFieldName(); //get the file(field or real file)'s name
if(item.isFormField()) {
System.out.println("just a simple field....");
String value = item.getString();
System.out.println(name + " = " + value );
req.setAttribute(name, value);
}else{
String value = item.getName();//this item is real file
System.out.println("got a real file");
int start = value.lastIndexOf("\\");
String filename = value.substring(start+1);//获得真正的文件名字,通常这一步转化只有在使用Opera浏览器时才需要使用
System.out.println("file name : " + filename);
req.setAttribute(name, filename);
File f1 = new File(path,filename);
OutputStream os = new FileOutputStream(f1);
InputStream is = item.getInputStream();
byte[] buffer = new byte[400];
int length;
while((length = is.read(buffer))!=-1) {
os.write(buffer, 0, length);
}
is.close();
os.close();
System.out.println("generate a file in the server.....");
req.getRequestDispatcher("index.jsp?&fileName=upload/" + filename).forward(req, resp);
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
try {
doGet(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
几个要点需要注意:
<form action="upload" method="post" enctype="multipart/form-data">来确保匿名上载文件的正确编码
upload.setHeaderEncoding("UTF-8");//set the encoding language保证Servlet端中文解码的正确性
上传的文件会被保存在D:\常用工具软件\ApacheServer\apache-tomcat-8.0.8\webapps\FileUploadDownLoad\upload这个目录下
前面的是安装的tomcat所在的目录 当然了也可以用MyEclipse内置的tomcat来运行项目,但是路径会有区别
资源页http://download.csdn.net/detail/lin19931006/8548537免费的哦