Arabic characters replaced with underscores "_" in file name when downloaded Spring boot / angular app

Viewed 18

been working on file upload/download project with spring boot / angular 14 locally, when encountered this problem : upload works fine with arabic filenames and saves files to a local folder, but when downloading them on the app , arabic characters are replaced with underscores "_" as shown below: enter image description here

<div class="card mt-3">
  <div class="card-header">لائحة المرفقات</div>
  <ul
    class="list-group list-group-flush"
    *ngFor="let file of fileInfos | async">
    <li class="list-group-item">
      <a href="{{ file.url }}" target="_blank" download="{{ file.name }}">{{ file.name }}</a>
    </li>
  </ul>

links are displayed on the app : http://localhost:8080/files/202211/نوت دوت.txt When inspecting the network exchange : enter image description here

@GetMapping("/files/{fileRef}/{filename}")
  public ResponseEntity<Resource> getFile( @PathVariable String filename,@PathVariable String fileRef) {

    Resource file = storageService.load(fileRef+'/'+filename);
    
    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
}

thought maybe enforcing the UTF-8 charset anyplace I could find would fix the problem :

HttpHeaders responseHeaders = new HttpHeaders();
 
 responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + file.getFilename() + "\"");
 responseHeaders.add("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); return
 ResponseEntity.ok().headers(responseHeaders).body(file);

used the New String(file.getFilename().getBytes(),Charset.forName("UTF-8") as file name to send, but no luck.. Arabic caracters in files names keeps turning to underscores.

when I set HttpHeaders.CONTENT_DISPOSITION value to "attachment; filename=" without adding the filename , files get downloaded with arabic name correctly but the files extention becomes ".htm" except for .doc files. (tried .txt, jpg, png, doc)

1 Answers

Found the solution:

HttpHeaders responseHeaders = new HttpHeaders();
 
responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"");
responseHeaders.add("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

return ResponseEntity.ok().headers(responseHeaders).body(file);

Used the ISO-8859-1 charset, replacing the %20 with space character. Now, when I download the files, arabic characters in the filename stay.

Related