Java文件上傳的實現方法有多種,以下是其中幾種常見的方法:
示例代碼:
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取上傳的文件
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
// 保存文件到指定路徑
String savePath = "C:/uploads/";
InputStream inputStream = filePart.getInputStream();
Files.copy(inputStream, Paths.get(savePath + fileName), StandardCopyOption.REPLACE_EXISTING);
// 返回上傳成功的提示信息
response.getWriter().println("File uploaded successfully");
}
}
示例代碼:
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 創建一個文件工廠對象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置文件上傳的臨時存儲路徑
String tempPath = "C:/temp/";
factory.setRepository(new File(tempPath));
// 創建文件上傳處理器對象
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 解析請求,獲取上傳的文件列表
List<FileItem> items = upload.parseRequest(request);
// 處理每個文件
for (FileItem item : items) {
// 判斷是否是普通表單字段還是文件字段
if (item.isFormField()) {
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// 處理普通表單字段的值
} else {
// 處理文件字段
String fileName = item.getName();
String savePath = "C:/uploads/";
item.write(new File(savePath + fileName));
}
}
// 返回上傳成功的提示信息
response.getWriter().println("File uploaded successfully");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("File upload failed");
}
}
}
以上是兩種常見的Java文件上傳的實現方法,開發者可以根據具體需求選擇適合的方法。