How to download zip file from reactjs using POST API.
The request is coming from nodejs in binary form
you can use jszip link https://github.com/Stuk/jszip like
import zipTargetFiles from '/path'
zipTargetFiles( data ).then(file => {
//operations
})
if you use fetch like this.
fetch('URL', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
//Body
})
}).then((response)=>{
//here is youu want zip data
var zip = new JSZip();
var zipData = response.data //
// Add an top-level, arbitrary text file with contents
zip.file("response.txt", zipData);
// Generate the zip file asynchronously
zip.generateAsync({type:"blob"})
.then(function(content) {
// Force down of the Zip file
saveAs(content, "zipFile.zip");
});
}).catch((error)=>{
console.log(error)
})
You can use JsZip on Client Side. Then, do a request with axios. Like this:
request = (currentUrl: string): Promise<void> => axios({
url: currentUrl,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const url: string = window.URL.createObjectURL(new Blob([response.data]));
});
Related
I am trying to send a file and some json in the same multipart POST request to my REST endpoint. The request is made directly from javascript using axios library as shown in the method below.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
formData.append("document", documentJson);
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Type field for document, while for file field Content-Type is application/pdf (I'm sending a pdf file).
On the server Content-Type for document is text/plain;charset=us-ascii.
Update:
I managed to make a correct request via Postman, by sending document as a .json file. Though I discovered this only works on Linux/Mac.
To set a content-type you need to pass a file-like object. You can create one using a Blob.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
Try this.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
// formData.append("document", documentJson); instead of this, use the line below.
formData.append("document", JSON.stringify(documentJson));
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
You can decode this stringified JSON in the back-end.
you only need to add the right headers to your request
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
})
You cant set content-type to documentJson, because non-file fields must not have a Content-Type header, see HTML 5 spec 4.10.21.8 multipart form data.
And there`s two way to achieve your goals:
JSON.stringify your data, and decode it in the back-end like this answer below
pass a file-like object and set Content-Type like this answer below
I need to upload file to server using fetch() from react native app
I have the following code in Angular which uses ng-file-upload:
in this function file variable is attached FormData
function addDocumentToMessage(messageId, file) {
data.filepath = file;
data.name = file.name;
return Upload.upload({
url: BackendUrl + "/messages/" + messageId + "/attachments/",
file: file,
data: data
})
.then(responseHandler)
.catch(errorHandler);
}
I tried to do following using fetch() but it doesn't work correctly: file is added to server but attachment and other fields are not saved there. Here is the code I tried:
document = { formData, name }
export const addDocumentToMessage = (token, logId, document) => {
const file = document.formData
const data = { filepath: file, name: document.name }
fetch(`${API_URL}/messages/${logId}/attachments/`, {
method: 'POST',
headers: { 'Authorization': `token ${token}`, 'Content-Type': 'multipart/form-data', Accept: 'application/json' },
body: JSON.stringify({ file: file, data: data })
})
.then(response => console.log(response.data))
.catch(error => console.log(error.message))
}
It seems that two Content-Types were mixed here:
multipart/form-data for sending binary content of the file in file
application/json for sending the some JSON data in body
Since HTTP requests only support one body having one Content-Type encoding we have to unify all of that to be multipart/form-data. The following example is using variable formData to combine (binary) file data with arbitrary JSON data.
export const addDocumentToMessage = (token, logId, document) => {
// commented these lines since I wanted to be more specific
// concerning the origin and types of data
// ---
// const file = document.formData
// const data = { filepath: file, name: document.name }
const fileField = document.querySelector("input[type='file']");
let formData = new FormData();
formData.append('file', fileField.files[0]);
formData.append('name'. fileField.files[0].name);
formData.append('arbitrary', JSON.stringify({hello: 'world'}));
fetch(`${API_URL}/messages/${logId}/attachments/`, {
method: 'POST',
headers: {
'Authorization': `token ${token}`,
'Accept': 'application/json'
// 'Content-Type': 'multipart/form-data',
},
body: formData
})
.then(response => console.log(response.data))
.catch(error => console.log(error.message))
}
The payload of HTTP request body would then look like this:
------WebKitFormBoundarypRlCB48zYzqAdHb8
Content-Disposition: form-data; name="file"; filename="some-image-file.png"
Content-Type: image/png
... (binary data) ...
------WebKitFormBoundarypRlCB48zYzqAdHb8
Content-Disposition: form-data; name="name"
some-image-file.png
------WebKitFormBoundarypRlCB48zYzqAdHb8
Content-Disposition: form-data; name="arbitrary"
{"hello":"world"}
------WebKitFormBoundarypRlCB48zYzqAdHb8--
References:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Uploading_a_file
https://developer.mozilla.org/de/docs/Web/API/FormData/append#Syntax
I am trying to send a file and some json in the same multipart POST request to my REST endpoint. The request is made directly from javascript using axios library as shown in the method below.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
formData.append("document", documentJson);
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Type field for document, while for file field Content-Type is application/pdf (I'm sending a pdf file).
On the server Content-Type for document is text/plain;charset=us-ascii.
Update:
I managed to make a correct request via Postman, by sending document as a .json file. Though I discovered this only works on Linux/Mac.
To set a content-type you need to pass a file-like object. You can create one using a Blob.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
Try this.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
// formData.append("document", documentJson); instead of this, use the line below.
formData.append("document", JSON.stringify(documentJson));
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
You can decode this stringified JSON in the back-end.
you only need to add the right headers to your request
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
})
You cant set content-type to documentJson, because non-file fields must not have a Content-Type header, see HTML 5 spec 4.10.21.8 multipart form data.
And there`s two way to achieve your goals:
JSON.stringify your data, and decode it in the back-end like this answer below
pass a file-like object and set Content-Type like this answer below
I'm switching from Jquery AJAX to react-dropzone & Axios, I'd like to upload a file to my Django server, I have no issue posting a blob url of the image on the server but I want to get it under request.FILES but I am getting an empty queryset.
request.FILES : <MultiValueDict: {}> <!--- empty
request.POST : <QueryDict: {}> <!--- able to get a blob url
Here's what my axios configuration looks like :
const temporaryURL = URL.createObjectURL(step3.drop[0]);
var fd = new FormData();
fd.append('image', temporaryURL);
axios({
method: 'post',
url: SITE_DOMAIN_NAME + '/business-card/collect/',
data: fd,
headers: {
"X-CSRFToken": CSRF_TOKEN,
"content-type": "application/x-www-form-urlencoded"
}
}).then(function (response) {
console.log(response)
URL.revokeObjectURL(temporaryURL);
}).catch(function (error) {
console.log(error)
});
I am receiving the file on a classBasedView on POST request.
How can I upload the file? Where am I wrong?
Edit
I also tried "application/form-data", doesn't solve the problem
the problem came from the content-type as it was using "application/form-data" instead of "multipart/form-data".
I am answering in case, someone comes here by searching on google:
let formData = new FormData();
formData.append('myFile', file);
formData.append('otherParam', 'myValue');
axios({
method: 'post',
url: 'myUrl',
data: formData,
headers: {
'content-type': 'multipart/form-data'
}
}).then(function (response) {
// on success
}).catch(function (error) {
// on error
});
I have used https://graph.microsoft.com/beta/me/photo/$value API to get the profile picture of the outlook user. I get an image on running the above API in the rest-client. The content-type of the API is "image/jpg"
But, in Node.js, the response of the API is as follows:
����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000�\u0000\u0005\u0005\u0005\u0005\u0005\u0005\u0006\u0006\u0006\u0006\b\t\b\t\b\f\u000b\n\n\u000b\f\u0012\r\u000e\r\u000e\r\u0012\u001b\u0011\u0014\u0011\u0011\u0014\u0011\u001b\u0018\u001d\u0018\u0016\u0018\u001d\u0018+"\u001e\u001e"+2*(*2<66<LHLdd�\u
I used 'fs' to create an image file. The code is as follows:
const options = {
url: "https://graph.microsoft.com/beta/me/photo/$value",
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${locals.access_token}`,
'Content-type': 'image/jpg',
}
};
request(options, (err, res, body) => {
if(err){
reject(err);
}
console.log(res);
const fs = require('fs');
const data = new Buffer(body).toString("base64");
// const data = new Buffer(body);
fs.writeFileSync('profile.jpg', data, (err) => {
if (err) {
console.log("There was an error writing the image")
}
else {
console.log("The file is written successfully");
}
});
});
The file is written successfully, but the .jpg image file generated is broken. I am unable to open the image.
The output of the image file is as follows:
77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve
You can do this by streaming the response like this,
request(options,(err,res,body)=>{
console.log('Done!');
}).pipe(fs.createWriteStream('./profile.jpg'));
https://www.npmjs.com/package/request#streaming
https://nodejs.org/api/fs.html#fs_class_fs_writestream
The reason for this is that by default, request will call .toString() on the response data. In case of binary data, like a RAW JPEG, this isn't what you want.
It's also explained in the request documentation (albeit vaguely):
(Note: if you expect binary data, you should set encoding: null.)
Which means that you can use this as well:
const options = {
encoding : null,
url : "https://graph.microsoft.com/beta/me/photo/$value",
method : 'GET',
headers : {
'Accept' : 'application/json',
'Authorization' : `Bearer ${locals.access_token}`,
'Content-type' : 'image/jpg',
}
};
However, streaming is probably still the better solution, because it won't require the entire response being read into memory first.
Request is deprecated. You can do this with axios;
// GET request for remote image in node.js
axios({
method: 'get',
url: 'http://example.com/file.jpg',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});