Java

Java WebAPI如何实现文件上传下载

小樊
127
2024-07-10 11:39:29
栏目: 编程语言

Java WebAPI可以通过使用Servlet来实现文件上传下载。以下是一个简单的示例:

  1. 文件上传
@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("文件上传成功");
    }
}
  1. 文件下载
@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头,然后将文件内容写入到输出流中实现文件下载。

0
看了该问题的人还看了