使用commons-fileupload组件上传文件

这是使用了commons-fileupload-1.2.1.jar 和 commons-io-1.4.jar这两个组件来上传文件的!

package upload;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//1、先获取工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//2、获取上传处理对象(要把工厂对象传递给它)
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(32768);//允许最大32KB
//3、解析请求参数,过滤掉不是文件上传框的参数
List<?> itemList = null;
try {
itemList = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}

for(int i = 0;i<itemList.size();i++){
FileItem fileItem = (FileItem)itemList.get(i);
System.out.println("文件名字为:"+fileItem.getName());

if(!fileItem.isFormField()){//判断是不是文件上传控件
//先获取客户端上传文件的File对象
System.out.println(fileItem.getName());
File sourceFile = new File(fileItem.getName());
System.out.println(sourceFile.getName());
//创建将要上传至服务器端的文件对象
File destFile = new File("D:\\temp", sourceFile.getName());
try {
fileItem.write(destFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}

System.out.println("上传成功");





}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值