java写一段文件上传的代码
时间: 2023-03-22 18:01:46 浏览: 118
好的,以下是一个Java文件上传的示例代码,使用了Apache Commons FileUpload库:
```java
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
public class FileUploadHandler {
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
public static void handleFileUpload(HttpServletRequest request, String uploadDir) throws Exception {
if (!ServletFileUpload.isMultipartContent(request)) {
throw new Exception("不是multipart/form-data类型的表单");
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = request.getServletContext().getRealPath("") + File.separator + uploadDir;
File uploadDirFile = new File(uploadPath);
if (!uploadDirFile.exists()) {
uploadDirFile.mkdir();
}
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
}
}
}
}
}
```
使用时,需要调用`handleFileUpload`方法,并传入HttpServletRequest对象和上传文件的保存目录:
```java
String uploadDir = "uploads";
FileUploadHandler.handleFileUpload(request, uploadDir);
```
注意:需要在`web.xml`文件中添加文件上传的配置,如下所示:
```xml
<servlet>
<servlet-name>fileUpload</servlet-name>
<servlet-class>org.apache.catalina.servlets.WebdavServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>fileUpload</servlet-name>
<url-pattern>/upload/*</url-pattern>
</servlet-mapping>
```
其中,`<servlet-class>`节点中的`WebdavServlet`可以替换为其他文件上传的Servlet类。
阅读全文