i want to download file from server in angular :
this code from service:
DownloadVerifyFile(requestId, fileId): any {
return this.httpClient
.get(this.appConfig.apiEndpoint + '/VerifyRequest/File/' + requestId + '/' + fileId,
{ responseType: 'blob' });
}
and this code for download that file in brwoser:
DownloadFile(fileId): void {
this.requestService.DownloadVerifyFile(this.id,fileId).subscribe(response => {
const a = document.createElement('a')
const objectUrl = URL.createObjectURL(response)
a.href = objectUrl
a.download = response;
a.click();
URL.revokeObjectURL(objectUrl);
});
}
but i have a problem with that , when i downlaod file , file name is this [object Blob] but i want to download by orginal name for example if file is file1.jpg , when downloaded file name must be fil1.jpg not [object Blob] . how can i solve this problem ???
Because you have named the file by response(It is an object). You were almost achieved. Just a little change as following:
a.download = response;
to
a.download = 'fil1.jpg';
Then you will get the correct file name.
Related
I'm messing with a piece of code to download a CSV from server. this is what I'm trying:
downloadCSVTemp(){
let name = 'report.csv';
const response = api.getReportCSV()
.then((res)=>{
const blob = new Blob([res], { type: "data:text/csv;charset=utf-8," });
const blobURL = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.download = name;
anchor.href = blobURL;
anchor.dataset.downloadurl = ["text/csv", anchor.download, anchor.href].join(
":"
);
anchor.click();
});
}
getReportCSV(){
return axios.get("/export/assessments/");
}
I intend to download a csv file from server url by an axios call, But this code is downloading an csv file which can't be opend by the browser & full of garbage data. What's the problem here ?
The res argument contains Axios response object. When creating the blob, you should use res.data:
new Blob([res.data], { type: "data:text/csv;charset=utf-8," });
I just want to ask, what is a good way to download file in Vue?
Because when I do it like this, it is not working, files are empty, and there is a problem with content-disposable, I dont't know if I can be sure that format is correct:
api.downloadFile(fileId).then(response => {
let blob = new Blob([response.data], { type: response.headers['content-type'] });
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "nameofFile" + '.pdf';
link.click();
}).catch(error=>{
console.log(error);
})
When this solution below is working, and it works perfectly, it downloads good file, with good content, format (formats can be different, pdf, png, txt etc.) and with good name but I don't think it goes through axios interceptors, so I don't think it is secured etc. (maybe im wrong)
downloadFile(fileId) {
console.log(fileId);
let link = document.createElement('a');
link.href = "http://localhost:8081/download?fileId=" + fileId;
link.click();
}
My axios method looks like this:
downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId).then(response=>{
return response;
})
Can somebody tell me how to do it in a good way with blob, content-disposable and secure solution?
My method on backend looks like this:
#GetMapping(value = "/download")
public ResponseEntity<Resource> download(#AuthenticationPrincipal User user,
#RequestParam("fileId") String fileId) throws FileNotFoundException {
Document file = storingService.loadFileByUsernameAndFileId(user.getUsername(), fileId);
Resource resource = new ByteArrayResource(file.getBinary().getData());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
.header(HttpHeaders.CONTENT_TYPE, file.getContentType())
.body(resource);
}
And response of this link: http://localhost:8081/download?fileId=xyz is:
I think the pdf showing up blank has to do with your axios call. You're going to want to add at least a response type.
downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId, { responseType: 'arraybuffer' })
.then(response=>{return response;})
The second object I'm passing to axios here is a config object. See their docs here.
Here's another Stack Overflow that I used to help me with a similar issue.
And here's another about the difference between 'arraybuffer' and 'blob'.
I am able to send a single image file to ReactJS. But I have to send multiple image files to ReactJS.
JAXRS code:
#GET
#Path("/download/file1")
#Produces( MediaType.APPLICATION_OCTET_STREAM )
public Response getFile() {
String fileName = DOWNLOAD_FILE_SERVER+"BMI/testcases/Basispath_BMI_0_out.gif";
File file = new File( fileName);
System.out.println("fileName inside getFile = "+fileName);
final String filename = "testcase1.gif";
System.out.println("filename inside getFile = "+filename);
// Create the JAXRS response
// Don't forget to include the filename in 2 HTTP headers:
//
// a) The standard 'Content-Disposition' one, and
// b) The custom 'X-Suggested-Filename'
final Response.ResponseBuilder builder = Response.ok(
file, MediaType.APPLICATION_OCTET_STREAM)
.header("X-Actual-Content-Length", file.length())
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
// All Done.
return builder.build();
}
ReactJS code:
downloadImage = () => {
axios({
url: 'http://localhost:9900/EXAMPLE/rest/myresource/download/file1',
method: 'GET',
responseType: 'blob',
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
var filename = 'Image1.gif'
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch((response) => { // then print response status
console.log("response = ",response);
})
}
Questions:
Is it possible to send multiple image files in the response of JAXRS?
How to receive multiple files in ReactJS GET response?
How to display received files in ReactJS?
Please provide solution to this issue.
I have below functionality using JavaScript
The back end gives me a URL to download a file from like below -
https://something.org/FILENAME.ZIP
So I file name is fixed as FILENAME.ZIP
But while downloading a file , the file should get downloaded with custom file name like CUSTOMFILENAME.ZIP instead of FILENAME.ZIP
So,
1)The file should get downloaded from URL : https://something.org/FILENAME.ZIP
2)But it should get saved with different file name as :
CUSTOMFILENAME.ZIP
3)I have tried below programme from url - how to download a file from url using javascript or jquery?
var a = document.createElement("a");
a.href = url;
var fileName = CUSTOMFILENAME;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();
But still file gets downloaded with whatever file name mentioned in URL
Can anybody please help me here ?
The file should get saved with CUSTOMFILENAME I provide and not fileName specified as part of URL
Try this see if it works,
const documentName = "CustomFileName"; // here your file name
fetch("http://yourdomain.com")
.then(res => {
return res.blob();
})
.then(blob => {
const href = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.download = documentName;
a.href = href;
a.click();
a.href = "";
})
.catch(err => console.error(err));
you are giving a object as download name give a string
I have a script to download different type files from server side. The code works for text/xml but when the downloaded pdf file is empty.
let response = this.http.get(this.Url , new Headers({responseType: 'blob'}))
.subscribe(doc => {
if (doc) {
let contentType = doc.headers.get("Content-Type");
let name = doc.headers.get("Content-Disposition").split("=")[1];
let blob = new Blob([doc.text()], {type: contentType});
let a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
},
error => this.msgService.showError(this.msgs, error));
My server
#GET
#Consumes(MediaType.APPLICATION_JSON)
#Path("-----")
public Response getDocument(#PathParam("documentId") Long documentId) throws Exception {
Document document = ---------------;
return ResponseHelper.createOkResponse(
output -> IOUtils.write(document.documentContent(), output),
document.documentName(),
document.documentType()
);
}
I can see the doc.text() is returning some byte[]. Also tried {responseType: 'arraybuffer'}. can anyone advise how can i display for pdf ?
Thanks