On Node Server i have this code . Its basically sending the browser POST data to api server and recieves a file as chunk data and the same data is send back to browser via pipe response . But the issue is the api reponse is correct and i can write the file using nodejs locally but it doesnt push download file in browser
router.post('/MyURLOnNODE', function (req, res) {
var MyJsonData = { some Data };
res.writeHead(200, {'Content-disposition': 'attachment; filename=fileArchive.tgz','Content-Type': 'application/force-download'});
try {
request({
url: 'SomeAPI Url', //URL to hit
method: 'POST',
json: MyJsonData
}).pipe(res);
} catch(e) {
console.log("Pipe error",e);
}
console.log("File Streaming Called ",MyJsonData)
}
);
Client Side Code ...This was an attempt to create a blob and use it on urlObject. but the downloaded file is corrupted when i checked in hex.
$http({
method: 'POST',
url: 'MyURLOnNODE',
data: PostData, //forms user object
headers: {
'Content-Type': 'application/json'
}
})
.then(function (data) {
var response=data.data;
var id = Flash.create('success', "Folder Archieved", 5000);
var a = document.getElementById('arch');
a.href = URL.createObjectURL(new Blob([response]));
a.download = "FolderMe.tgz";
a.type='application/octet-stream '
a.click();
}
So is there any solution to this ? either on NodeJs Side or On browser
Update : https://stackoverflow.com/a/7969061/7078299
This thread says its hard to convert an ajax request to download file. So i need to work on client on using urlobject. But blob isnt working with stream data. How to solve it
You can use a node module called file-saver and use saveAs method provided by it and download the file on the client side.
First npm install file-saver;
You can use it as
import {saveAs} from 'file-saver';
and inside your then block you need to add this line
saveAs(new Blob([response]), <your file name>)
It will auto-download your file.
i fixed the issue by adding a reponseType on Client Side Code. Now the blob and ObjectUrl works correctly
$http({
method: 'POST',
url: 'MyUrl',
data: PostData, //forms user object
headers: {
'Content-Type': 'application/json'
},
responseType: 'arraybuffer'
})
.then(function (response) {
console.log(response);
var headers = response.headers();
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Archive.tgz";
link.click();
});
Related
I am getting the attachment body using the Rest API.
var config = {
method: 'get',
url: '<Domanin>/services/data/v48.0/sobjects/Attachment/00PD000000HQD68MAH/Body',
headers: {
'Authorization': `Bearer ${
accessToken
}`,
'content-type':'application/pdf'
},
};
let rawData = await axios(config);
rawData = rawData.data
I am getting the PDF data in this format
%PDF-1.5
%ÓôÌá
1 0 obj
<<
In the client side I am trying to make this as a downloadable file but I am getting blank pdf. The actual pdf contains 2 pages the downloaded pdf contains two pages as well but they are blank.
Client Side Code:
var downloadLink = document.createElement('a');
downloadLink.target = '_blank';
downloadLink.download = 'test.pdf';
// convert downloaded data to a Blob
var blob = new Blob(([rawData]), {type: 'application/pdf'});
// create an object URL from the Blob
var downloadUrl = URL.createObjectURL(blob);
// set object URL as the anchor's href
downloadLink.href = downloadUrl;
// append the anchor to document body
document.body.append(downloadLink);
// fire a click event on the anchor
downloadLink.click();
Please let me know what is wrong with the above logic
Please specify responseType: 'arraybuffer' in request config. Modify your config object to
{
method: 'get',
url: '<Domanin>/services/data/v48.0/sobjects/Attachment/00PD000000HQD68MAH/Body',
headers: {
'Authorization': `Bearer ${
accessToken
}`
},
'responseType': 'arraybuffer'
};
I'm trying to update a local JPG image file into an S3 bucket using the REST PUT request and Axios.
I managed to send the PUT request and to get a positive answer from AWS S3 Service but what it's been upload is not a JPG file but a JSON file.
This is the code that I'm using:
//Create the FormData
var data = new FormData();
data.append('file', fs.createReadStream(image_path));
//Send the file to File-system
console.log("Sending file to S3...");
const axiosResponse = await axios.put(image_signed_url, {
data: data,
headers: { 'Content-Type': 'multipart/form-data' }
}).catch(function(error) {
console.log(JSON.stringify(error));
return null;
});
I have already try to change the headers to {'Content-Type': 'application/octet-stream' } but I obtained the same result.
It did not manage to make AXIOS work in order to upload an image.
The node-fetch module did it sending the image as a binary and specifying the "Content-type".
If I try to the same using AXIOS it the image was always packet into a form-data and the result was JSON file uploaded into the S3 bucket instead of the image.
//Send the file to File-system
console.log("Sending file to S3...");
const resp = await fetch(image_signed_url, {
method: 'PUT',
body: fs.readFileSync(image_path),
headers: {
'Content-Type': 'image/jpeg',
},
}).catch( err => {
console.log(err);
return null;
});
I'm trying to send an image through axios POST request. The request is going through, but the image is not uploading.
Here is my code,
const screenshotPath = path.join(os.tmpdir(), 'screenshot.png');
var bodyFormData = new FormData();
//bodyFormData.append('uploadedFile', screenshotPath);
bodyFormData.append('uploadedFile', fs.createReadStream(screenshotPath));
axios({
method: 'post',
url: url,
data: bodyFormData,
config: {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: 'Bearer ' + token
}
}
})
Is it because of the filename path ?
this is my screenshotPath
C:\Users\oem\AppData\Local\Temp\screenshot.png
You are using createReadStream function from the File System library of Node. But Node is running on server-side and here you are working with a react application which is running on client side.
Please check MDN documentation on how to upload files from front-end applications.
Frontend will send a post request to Scala Play Framework API to download a file. The response header is like :
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8000
Content-Disposition:attachment;
filename="logo_10248191299068944166699.png";
filename*=utf-8'logo_10248191299068944166699.png
Content-Length:53765
Content-Type:image/png
Date:Thu, 07 Sep 2017 13:05:57 GMT
Vary:Origin
My react js code is as below:
const FileDownload = require('react-file-download')
axios(req).then(response => (response.status === 200? response :
null)).then(res =>
{
FileDownload(res.data, filename)
})
It can be downloaded automatically but the file cannot be read. For example, if I download an image, the image cannot be rendered. If I download a zip file, it cannot be extracted. I already tried React-FileDownload, FileSaver, convert the res.data into arraybuffer with the creation of 8 bit array for loop - I.Just.Cant.Make.It.Work.
When I erase the extension format from ubuntu and open it on Atom, these shows up. And from the download tab in Chrome, it stated blob:http://localhost:8000/4de5d808-67a6-4d4e-9920-24bd342664f6
�PNG
IHDRwB���gAMA���asRGB���
cHRMz&�����u0�`:�p��Q<bKGD�������
pHYs.#.#x�?v�IDATx���w�e�Y����9WܹrN]]�-����0�2��,����t|
�=w�{ƹ�&����`LI��`0&I�J��j�����}��J���Pa�=W�~����ݭ��jϵ~�}��1`�|�;��֟zQj�?xz�����z�N-�^n5��$�m�:Uv��Sv�]�N��%=✾s����V��Ǜ?l����>$)��7��p�y{B]]�Ò�T��J:i�̥���+.�V5����$����u����u^�����-��%��tJ��ً�[��8��$}���UOI�{]v��N�3k�I�!�+$}�����I'���cW���_sNF�DҏI�Ip�9��$�`��
I solved the problem. It lies in the POST request.
url: url + '/storage/download_file',
method: 'POST',
responseType: 'blob', //THE KEY TO SUCCESS
headers: {
Authorization: 'Bearer ' + token,
Accept: 'application/json',
'Content-Type': 'application/json'
}
Have to add responseType: 'blob'
I changed to FileSaver to download file.
var blob = new Blob([res.data], {type: "application/octet-stream"});
FileSaver.saveAs(blob, filename)
Solution above is working but I don't like to install excessive packages
Axios
url: '/url
responseType: 'blob'
JS
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.href = url;
link.download = fileName;
document.body.appendChild(link); // optional
link.click();
document.body.removeChild(link); // optional
I am using axios to upload image file to server but failed. Below is the code:
let data = new FormData()
data.append('image', image)
axios({
type: type,
payload: {
request: {
url: url,
method: 'post',
timeout: 60000,
headers: {
'ACCESS_TOKEN': token,
'Content-Type': 'multipart/form-data',
},
data: data
}
})
I got 400 Bad Request error. Below is the response from server:
{"timestamp":1480851939951,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'image' is not present.","path":"/upload/image"}
I have used postman to test the server api and it works fine. What wrong with my code?
EDIT1
The image object was got from . Below is the code to get the image object
var fr = new FileReader();
fr.onload = function () {
let image = fr.result() //image is got here
}
fr.readAsDataURL(file);