Java WebAPI可以通過使用Servlet來實現文件上傳下載。以下是一個簡單的示例:
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
// 保存文件到指定目錄
File file = new File("C:/upload/" + fileName);
try (OutputStream out = new FileOutputStream(file)) {
IOUtils.copy(fileContent, out);
} catch (IOException e) {
e.printStackTrace();
}
response.getWriter().println("文件上傳成功");
}
}
@WebServlet("/download")
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = "example.txt";
File file = new File("C:/upload/" + fileName);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
try (InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream()) {
IOUtils.copy(in, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
在以上示例中,通過MultipartConfig注解標記文件上傳Servlet,并使用Part對象獲取上傳的文件,然后將文件保存到指定目錄。在文件下載Servlet中,設置響應的Content-Type和Content-Disposition頭,然后將文件內容寫入到輸出流中實現文件下載。