用java写一个上传附件的代码,支持多附件上传
时间: 2023-05-23 14:07:08 浏览: 101
A:以下是一个简单的用java写的多附件上传代码。首先需要依赖于相关的jar包(如commons-fileupload和commons-io),然后通过Servlet处理上传的请求:
```java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
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;
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置上传文件的保存路径
String savePath = request.getServletContext().getRealPath("/uploads");
// 创建文件上传处理器
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setFileSizeMax(1024 * 1024 * 10); // 10 MB
uploader.setSizeMax(1024 * 1024 * 100); // 100 MB
try {
// 解析请求,获取上传的文件列表
List<FileItem> fileItems = uploader.parseRequest(request);
// 遍历文件列表
for (FileItem fileItem : fileItems) {
if (!fileItem.isFormField()) { // 如果是文件类型
String fileName = new File(fileItem.getName()).getName();
String filePath = savePath + File.separator + fileName;
File storeFile = new File(filePath);
// 保存文件到硬盘
fileItem.write(storeFile);
}
}
request.setAttribute("message", "文件上传成功!");
} catch (Exception ex) {
request.setAttribute("message", "上传失败: " + ex.getMessage());
}
// 跳转到上传结果页面
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
```
上述代码实现了从请求中解析出上传的文件,遍历文件列表并将它们保存到硬盘的功能。其中,`@MultipartConfig`注解告诉Servlet容器这是一个支持文件上传的Servlet,`ServletFileUpload`类是Apache Commons FileUpload库提供的功能强大的上传处理器。
阅读全文