开发步骤:
先给大家介绍了要用到的两个类:
(1)DIskFileItemFactory对象:用于设置缓存大小和缓存目录
(2)ServletFileUpload对象:来解析文件
1】导两个jar包 commons-fileupload-1.2.2.jar 右键Build Path --> add path
commons-io-2.0.1.jar 右键Build Path --> add path
在E盘下新建一个文件夹为TestData,在文件夹中新建两个文件夹:FileTemp该文件夹存放缓存文件,server该文件夹存放服务器发过来的文件;若上传的文件大小大于自己设置的缓存大小,则进入缓存文件夹FileTemp,否则进入server文件夹。
2】先写好load.html代码,代码如下:
<!DOCTYPE html>
<meta charset="utf-8"/>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<!-- enctype="multipart/form-data"为表单提交内容的类型 -->
<form action="/October1003/loadsingle" method="post" enctype="multipart/form-data">
<input type = "file" name = "filename" ><br>
<input type="submit" value="上传">
</form>
</body>
</html>
3】新建一个名为 “ LoadServlet ” 的Servlet,该Servlet的url为load ,代码如下:
package com.fileload;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
public class LoadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//使用工具进行文件上传
//1 DiskFileItemFactory 设置缓存大小和缓存目录
DiskFileItemFactory factory = new DiskFileItemFactory(10*1024,new File("E://TestData/FileTemp"));
//2 ServletFileUpload 解析文件
ServletFileUpload upload = new ServletFileUpload(factory);
//3 设置文件头的乱码问题
upload.setHeaderEncoding("utf-8");
//4 解析文件
try {
List<FileItem> list = upload.parseRequest(request);
if(list != null){
//获取第一个文件
FileItem item = list.get(0);
//获取文件信息
String name = item.getName();
String type = item.getContentType();
long size = item.getSize();
//获取文件内容 不包含其他
InputStream in = item.getInputStream();
//把文件传到电脑硬盘上
FileUtils.copyInputStreamToFile(in,new File("E://TestData/server"+name));
//文件上传成功后 把临时文件删除
item.delete();
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
4】部署项目,开启服务器
在浏览器中访问:1)首先访问load.html 访问地址为:http://localhost:8080/包名/load.html
2)点击选择文件,然后上传
3)点击上传后,网页会跳转到地址为http://localhost:8080/包名/load (load为url的servlet)
4)进入E盘目录下的TestData中查看是否上传成功。
原文地址:https://www.cnblogs.com/xsy20181001/p/9740955.html