java的文件批量上传
时间: 2023-11-20 14:54:11 浏览: 117
Java的文件批量上传可以使用Apache Commons FileUpload库来实现。以下是一个简单的示例代码:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
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;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 检查是否为文件上传请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println("请选择要上传的文件!");
return;
}
// 创建文件上传工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置缓冲区大小和临时文件目录
factory.setSizeThreshold(1024 * 1024);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// 创建文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件的大小限制
upload.setFileSizeMax(1024 * 1024 * 10);
try {
// 解析上传请求
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// 如果是普通表单字段,则输出其名称和值
if (item.isFormField()) {
out.println(item.getFieldName() + ": " + item.getString("UTF-8") + "<br/>");
} else {
// 如果是文件字段,则保存文件到服务器
String fileName = item.getName();
String filePath = "C:/uploads/" + fileName;
File uploadedFile = new File(filePath);
item.write(uploadedFile);
out.println("文件上传成功!<br/>");
}
}
} catch (FileUploadException e) {
out.println("文件上传失败:" + e.getMessage());
} catch (Exception e) {
out.println("文件上传失败:" + e.getMessage());
} finally {
out.close();
}
}
}
```
该示例代码使用了Apache Commons FileUpload库来解析上传请求,并将上传的文件保存到服务器上的指定目录。在处理上传请求时,该代码还可以输出普通表单字段的名称和值。你可以根据自己的需求修改该示例代码。
阅读全文