\struts2\src\com\test\servlet

本文介绍了一个使用Java Servlet和Apache Commons FileUpload库实现的文件上传功能。该Servlet通过配置临时文件存储路径及大小限制来解析HTTP请求中的文件项,并将文件保存到指定目录。
摘要由CSDN通过智能技术生成
package com.test.servlet;

import java.io.File;
import java.io.IOException;
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;

public class UploadServlet extends HttpServlet
{

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
DiskFileItemFactory factory = new DiskFileItemFactory();

String path = request.getRealPath("/upload");

factory.setRepository(new File(path));

factory.setSizeThreshold(1024 * 1024);

ServletFileUpload upload = new ServletFileUpload(factory);

try
{
List<FileItem> list = upload.parseRequest(request);

for (FileItem item : list)
{
if (item.isFormField())
{
String name = item.getFieldName();

String value = item.getString("gbk");

System.out.println(name);

request.setAttribute(name, value);
}
else
{
String name = item.getFieldName();

String value = item.getName();

int start = value.lastIndexOf("\\");

String fileName = value.substring(start + 1);

request.setAttribute(name, fileName);


item.write(new File(path,fileName));


// OutputStream os = new FileOutputStream(new File(path,
// fileName));
//
// InputStream is = item.getInputStream();
//
// byte[] buffer = new byte[400];
//
// int length = 0;
//
// while ((length = is.read(buffer)) > 0)
// {
// os.write(buffer, 0, length);
// }
//
// os.close();
//
// is.close();

}
}

}

catch (Exception ex)
{
ex.printStackTrace();
}
request.getRequestDispatcher("upload/result2.jsp").forward(request,
response);

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值