实现文件上传的完整java代码
时间: 2024-09-30 07:15:38 浏览: 29
在Java中实现文件上传通常涉及到Servlet、MultipartHttpServletRequest以及File类型的处理。以下是一个简单的示例,展示了一个基于Apache Commons FileUpload库的文件上传过程:
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.FileItem;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private File uploadDirectory = new File("path/to/upload/directory");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建一个临时目录用于处理上传文件
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem item : fileItems) {
if (!item.isFormField()) { // 检查是否为表单字段,如果是,则忽略
String fileName = FilenameUtils.getName(item.getName());
InputStream inputStream = item.getInputStream();
// 将文件保存到指定目录
File uploadedFile = new File(uploadDirectory, fileName);
OutputStream outputStream = new FileOutputStream(uploadedFile);
byte[] bytes = new byte[4096];
int length;
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
outputStream.close();
inputStream.close();
System.out.println("File " + fileName + " uploaded successfully.");
} else {
System.out.println("This is a form field.");
}
}
} catch (Exception e) {
e.printStackTrace();
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "File upload failed.");
}
}
}
```
阅读全文