티스토리 뷰

증상

서버에서 파일을 읽어오다가 실패하면서 console에 "net::ERR_CONTENT_LENGTH_MISMATCH 200" 출력

 

원인

서버에서 읽어오는 파일의 크기와 Header에 설정된 파일의 Content-Length의 크기가 달라서 발생

 

해결

upload 할 때 파일 크기를 추출해서 DB에 저장한다.

@PostMapping("/uri")
public String upload(@RequestParam("file") MultipartFile file) {
  Object obj = new Object();
  obj.setFileSize((int) file.getSize());	//MultipartFile의 getSize() 메소드로 파일 크기를 추출한다.
  service.insert(obj);	//추출한 파일 크기를 DB에 INSERT 한다.
  return "str";
}

 

download 할 때 DB에 저장된 크기를 읽어서 Header에 입력한다.

@GetMapping("/uri")
public void download(HttpServletResponse response) {
  Object obj = service.select();
  int fileLength = obj.getFileSize();
  response.setHeader("Content-Length", "" + fileLength);	//파일 크기를 header 정보에 set한다.

  try (
  	FileInputStream fis = new FileInputStream(saveFileName);
  	OutputStream out = response.getOutputStream();
  ) {
    int readCount = 0;
    byte[] buffer = new byte[1024];
    while ((readCount = fis.read(buffer)) != -1) {
      out.write(buffer, 0, readCount);
    }
  } catch (Exception ex) {
  	throw new RuntimeException("file Save Error");
  }
}

 

참고

takeknowledge.tistory.com/62?category=790021

댓글
Total
Today
Yesterday
링크
Apple 2023 맥북 프로 14 M3, 스페이스 그레이, M3 8코어, 10코어 GPU, 512GB, 8GB, 한글