使用commons file upload上传本地文件
时间: 2024-04-30 22:19:22 浏览: 68
你可以使用Apache Commons FileUpload库来上传本地文件。以下是一个简单的示例代码:
1. 首先,你需要在项目中添加commons-fileupload和commons-io库的依赖,可以在Maven或Gradle中添加以下依赖:
Maven:
```
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
```
Gradle:
```
implementation 'commons-fileupload:commons-fileupload:1.4'
implementation 'commons-io:commons-io:2.8.0'
```
2. 在你的Servlet或Controller中,编写以下代码:
```
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) { // 判断是否是文件类型
String fileName = item.getName();
String filePath = "/path/to/upload/folder/" + fileName;
File uploadedFile = new File(filePath);
item.write(uploadedFile);
}
}
response.getWriter().println("File uploaded successfully!");
} catch (Exception e) {
response.getWriter().println("File upload failed!");
e.printStackTrace();
}
}
}
}
```
这个示例代码将上传的文件保存在`/path/to/upload/folder/`路径下。你可以根据你的实际情况修改保存路径。
3. 在前端,你可以使用HTML表单来上传文件:
```
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
```
当用户单击“上传”按钮时,表单将提交到`/upload`URL,然后Servlet将处理上传的文件。
阅读全文