要使用commons-fileupload上傳圖片,可以按照以下步驟進行:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = "/path/to/save/" + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
}
}
response.getWriter().println("File uploaded successfully!");
} catch (Exception e) {
response.getWriter().println("Error uploading file: " + e.getMessage());
}
} else {
response.getWriter().println("No file uploaded!");
}
}
}
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.example.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
通過以上步驟,你就可以使用commons-fileupload庫來上傳圖片或其他文件了。記得在實際項目中進行適當的錯誤處理和文件存儲路徑配置。