Frank
Frank

Reputation: 1027

how to download the file that uploading

I am developing an upload feature from excel files, after I parse the uploading excel file and modify some values in Workbook, how to download the Workbook? below as my upload interface:

public void batchImport(HttpServletResponse response, MultipartFile file) {
    String fileName = file.getOriginalFilename();
    boolean isExcel2003 = true;
    if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
      isExcel2003 = false;
    }
    InputStream is = file.getInputStream();
    if (isExcel2003) {
      Workbook wb = new HSSFWorkbook(is);
    } else {
      Workbook wb = new XSSFWorkbook(is);
    }
    // some logic to handle wb

    // download an excel by the Workbook
    response.setHeader("content-Type", "application/vnd.ms-excel");
    response.setHeader(
        "Content-Disposition",
        "attachment;filename="
            + URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20").replaceAll("_", "\\/"));
    wb.write(response.getOutputStream()); 
}

I debug it at download line, the wb value is right, no errors but download nothing. how could I modify it?

Upvotes: 0

Views: 178

Answers (1)

Marc Stroebel
Marc Stroebel

Reputation: 2357

@PostMapping(value = Mappings.UPLOAD)
@ResponseBody
public void upload( MultipartFile file, HttpServletResponse response)

A void method has no return type, so there's no response body. You need to specify return type e.g. ResponseEntity and return a value.

Or remove ResponseBody annotation.

Look here for samples: https://www.baeldung.com/spring-mvc-image-media-data

Upvotes: 1

Related Questions