给大家推荐个靠谱的公众号程序员探索之路,大家一起加油
package com.lean.zzh;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.management.RuntimeErrorException;
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;
public class FileUpload extends HttpServlet {
/**
* Constructor of the object.
*/
public FileUpload2() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 判断上传的表单的数据类型是不是multipart/form-data
boolean isMulForm = ServletFileUpload.isMultipartContent(request);
if (!isMulForm) {
throw new RuntimeException("你的表单格式 不对");
}
// 常规的file上传逻辑
// 创建‘能够创建上传文件对象’的“工厂”
DiskFileItemFactory factory = new DiskFileItemFactory();
// 上传文件的对象
ServletFileUpload fileUpload = new ServletFileUpload(factory);
// 设置字符编码
fileUpload.setHeaderEncoding("utf-8");
// 设置文件上传文件的大小 ,不可超过2M
fileUpload.setFileSizeMax(2 * 1024 * 1024);
// 设置文件总大小 , 不可超过5M
fileUpload.setSizeMax(5 * 1024 * 1024);
// 把表单提交过来的数据进行解析
try {
// FileItem表单项,有的项里面包含文件,有的不包含文件 对他们进行区别对待
List<FileItem> fileItems = fileUpload.parseRequest(request);
// 获取每一项的数据
for (FileItem item : fileItems) {
if (item.isFormField()) {
// 它是一个普通数据项,不是文件项
processFormField(item);
} else {
// 这是一个包含文件的项
processFileUpload(item);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
// 对于普通的表单项
private void processFormField(FileItem item) {
// 得到名字
String name = item.getFieldName();
// 得到值
String value = "";
try {
value = item.getString("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + ":" + value);
}
// 对于包含文件的表单项
private void processFileUpload(FileItem item) {
// 在应用目录下保存这个文件 对于现在来讲就是Tomcat里
String storeDirectory = getServletContext().getRealPath("/upload");
// 创建文件的目录对象
File realDirectory = new File(storeDirectory);
// 判断目录是否存在
if (!realDirectory.exists()) {
// 如果不存在就创建 这个创建方法如果有字目录也会一并创建
realDirectory.mkdirs();
}
byte[] dataByte = new byte[1024];
int len = 0;
InputStream in = null;
FileOutputStream write = null;
try {
// 拿到文件的读取流
in = item.getInputStream();
// 得到文件上传的文件名
String fileName = item.getName();
// 获得保存上传文件的路径
File realFile = new File(realDirectory, fileName);
// 获得文件保存流
write = new FileOutputStream(realFile);
while ((len = in.read(dataByte)) != -1) {
write.write(dataByte, 0, len);
write.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭流 若过不关闭会发生操作系统中读者和写着问题,也就是,文件打不开,别占用着
// 其实是 操作系统中读者一个锁,写者一个锁,当读者锁文件中写者无法访问,反之同样
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (write != null) {
try {
write.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}