Servlet文件上传功能的实现!
声明:使用了第三方fileupload jar包
commons-fileupload-1.2.1.jar 以及commons-io-1.3.2.jar
1.创建DiskFileItemFactory 磁盘文件条目工厂—-对象
2.创建ServletFileUpload 文件上传对象 构造方法传“工厂”
3.用文件上传对象的isMultipart()方法request请求是否为文件上传–不是则return
4.用文件上传对象的parseRequest()方法转换request为文件对象 返回List集合对象
5.遍历每一个FileItem,并判断item是否为表格区域,如果是执行相应操作,如果不是执行不同的操作
package com.stx.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
/*
*@author:David admin@dxscx.com
*@Version: 1.0
*@Description: What do you want to do?
*@Time:2016-5-31 下午5:53:49
*/
public class Upload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
//实例化磁盘文件条目工厂
DiskFileItemFactory factory =new DiskFileItemFactory();
//实例化Servlet文件上传对象
ServletFileUpload upload=new ServletFileUpload(factory);
//判断request请求是否为文件上传
if(!upload.isMultipartContent(request)){
return;
}
//获得转换后的文件list集合
FileOutputStream fos=null;
InputStream is =null;
try {
List<FileItem> list=upload.parseRequest(request);
//遍历集合list
for(FileItem item:list){
//判断是否为表格数据
if(item.isFormField()){
//表格内容处理相应(键值对)
String key_name=item.getFieldName();//获取字段名
String key_value=item.getString();//获取相应值
//System.out.println(key_name);
System.out.println("key_name:\t"+key_name+",key_value:\t"+key_value);
}else{
//上传为文件内容
String filename=item.getName();
System.out.println("文件名:"+filename);
//获取项目实际路径存储于upload文件夹下
String path = getServletContext().getRealPath("/")+"upload\\";
//判断该路径是否为文件夹或者已经存在,不能同事满足则创建文件夹
File file = new File(path);
if(!(file.isDirectory()&file.exists())){
file.mkdirs();
}
//System.out.println(path); 输出路径查看测试
//创建文件输出流对象
fos=new FileOutputStream(path+filename);
//从上传的文件获得输入流
is = item.getInputStream();
byte[] b = new byte[1024];
int len = -1;
//读取输入流写入文件
while((len=is.read(b))!=-1){
fos.write(b, 0, len);
fos.flush();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}finally{
fos.close();
is.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}