天天看點

rpc 實作檔案下載下傳 Java Spring Boot

@RequestMapping("/file")
@ResponseBody
public void file(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("file");
    String path = "/file" + File.separator + name;
 
    File imageFile = new File(path);
    if (!imageFile.exists()) {
        return;
    }
 
    //下載下傳的檔案攜帶這個名稱
    response.setHeader("Content-Disposition", "attachment;filename=" + name);
    //檔案下載下傳類型--二進制檔案
    response.setContentType("application/octet-stream");
 
    try {
        FileInputStream fis = new FileInputStream(path);
        byte[] content = new byte[fis.available()];
        fis.read(content);
        fis.close();
 
        ServletOutputStream sos = response.getOutputStream();
        sos.write(content);
 
        sos.flush();
        sos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }      

繼續閱讀