Download e salvamento de arquivos do servidor usando o AngularJS
Estou com o seguinte problema e não consigo encontrar resolução. Criei um endpoint com o Spring Boot e quando estou usandoCarteiro Estou recebendo resposta com imagem a pedido do corpo.
Mas quando estou tentando baixar e salvar arquivos no computador usando Angular e Blob e FileSaver, meu arquivo salvo não consegue ler.
Este é o meu controlador angular:
vm.download = function (filename) {
console.log("Start download. File name:", filename);
$http.get('api/files/download/' + filename)
.then(function (response) {
console.log(data);
var data = new Blob([response.data], {type: 'image/jpeg;charset=UTF-8'});
FileSaver.saveAs(data, filename);
})
}
e aqui está o meu ponto final:
@RequestMapping(value = "/files/download/{id:.*}", method = RequestMethod.GET)
@ResponseBody
@Timed
public void DownloadFiles(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
MongoClient mongoClient = new MongoClient();
DB mongoDB = mongoClient.getDB("angularspingproject");
BasicDBObject query = new BasicDBObject();
query.put("filename", id);
GridFS fileStore = new GridFS(mongoDB, "fs");
GridFSDBFile gridFSDBFile = fileStore.findOne(query);
if (gridFSDBFile != null && id.equalsIgnoreCase((String) gridFSDBFile.getFilename())) {
try {
response.setContentType(gridFSDBFile.getContentType());
response.setContentLength((new Long(gridFSDBFile.getLength()).intValue()));
response.setHeader("content-Disposition", "attachment; filename=" + gridFSDBFile.getFilename());
IOUtils.copyLarge(gridFSDBFile.getInputStream(), response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("IOError writting file to output stream");
}
}
}
Meu cabeçalho:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 316707
Content-Type: image/jpeg;charset=UTF-8
Pragma: no-cache
Server:Apache-Coyote/1.1
X-Application-Context : angularspingproject:8080
X-Content-Type-Options : nosniff
X-XSS-Protection: 1; mode=block
content-Disposition: attachment; filename=main_page.jpg
@EditarProblema resolvido
vm.download = function (filename) {
$http.get('api/files/download/' + filename, {responseType:'blob'})
.then(function (response) {
console.log(response);
var data = new Blob([response.data], {type: 'image/jpeg;charset=UTF-8'});
FileSaver.saveAs(data, filename);
})
}
Adicionei responseType: 'blob' a $ http