upload image file converted from html to s3 - reactjs

I have a piece of HTML which I converted into an image using html-to-image and now I need to upload that image file to s3.
What I get after conversion is base 64 url. I have my s3 setup on remote backend where I send files to the api route and it uploads it to s3 and returns the s3 url for the file.
How can I convert this base url to image obj and send it to the api?
Function to convert html to img:
htmlToImage.toPng(document.getElementById('my-node'))
.then(function (dataUrl) {
// do stuff with url
});

There is a pretty simple common function which converts image data url to a file object defined as following:
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type:mime });
}
// Usage in your case
htmlToImage.toPng(document.getElementById('my-node'))
.then(function (dataUrl) {
const yourFile = dataURLtoFile(dataUrl, 'yourImageName');
});

Related

Flutter Monitor FileUpload progress using the http package

I have been using the following code to upload files on my server as it is doing the job but i want to monitor the Upload Progress Percentage during the opration and Update the UI accordingly to reflect the prgress to the user
uploadFile({File imageFile, String refCode}) async {
// open a bytestream
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
// get file length
var length = await imageFile.length();
// string to uri
var uri = Uri.parse(
'http://-------------/api/FilesUploadB/?refCode=$refCode');
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
//return response.
}
NOTE that the value in the listen is getting me the final return from the WebAPI on the server.
how to achieve that?
Take a look at this example on GitHub. It demonstrates how you can access the current upload progress of your file.

How to upload audio file to Firebase Storage?

I'm trying to upload audio file to Firebase Storage in my Ionic2 project.
First I recorded a audio file using Media plugin (Cordova plugin), and this file is playing well. From the Android storage and from the media plugin method (this.media.play()...;).
Second I need to push the recorded file to Firebase Storage.
this is my code:
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
let filePath = `${this.file.externalDataDirectory}`+`${this.fileName}`;
const voiceRef = storageRef.child(`voices/${this.fileName}`);
var blob = new Blob([filePath], {type: 'audio/mp3'});
voiceRef.put(blob);
After reading the Firebase doc, I can push blob to Firebase.
The file is successfully pushed to Firebase Storage with empty data (95 Byte).
this is screenshot:
The problem isn't a Firebase issue
My problem is solved by using the File cordova plugin method (readAsDataURL()) and the putString(fileBase64,firebase.storage.StringFormat.DATA_URL) method.
First, I create a file reference:
let filePath = "this.file.externalDataDirectory" + "this.fileName";
Then I transform the file to a base64 string by using the readAsDataURL method that returns a promise containing the file as a string base64. Also, I push the file to Firebase using the putString method that has two parameters the File that returned by the readAsDataURL and the second is firebase.storage.StringFormat.DATA_URL.
My Final code:
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
let filePath = `${this.file.externalDataDirectory}` + `${this.fileName}`;
this.file.readAsDataURL(this.file.externalDataDirectory, this.fileName).then((file) => {
let voiceRef = storageRef.child(`voices/${this.fileName}`).putString(file, firebase.storage.StringFormat.DATA_URL);
voiceRef.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => {
console.log("uploading");
}, (e) => {
reject(e);
console.log(JSON.stringify(e, null, 2));
}, () => {
var downloadURL = voiceRef.snapshot.downloadURL;
resolve(downloadURL);
});
});
That's working fine for me.
Thanks.

How to automatically download a xlsx file(in angularjs 1) sent by server

The HTTP response for a POST request that I am getting from server side is a xlsx file.How do I download the file in angularjs 1?
Note: res.download() won't work here,since its a POST request that I am making,and res.download() works only for GET request
The following shall work :
$http.post("url_here", post_data_to_send, {responseType: 'arraybuffer'})
.success(function (data,status,headers) {
var blob = new Blob([data]);
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display:none";
a.href = objectUrl;
a.download = headers().filename;
a.click();
console.log("Report downloaded");
}).error(function (err) {
console.log(err);
});
You can do it directly on Client Side, you may have some cross-browser compatibility issues (the best way is always to provide a download stream via server, for large files for example).
// this example uses a JSON String
// but you can do it with any valid blob argument
const fileContent = [JSON.stringify(
['something', 'to', 'download'], null, 2
)];
const downloader = document.createElement('a');
// set the filename here
downloader.download = 'filename.json';
const blob = new Blob(fileContent, {type: 'text/plain'});
downloader.href = window.URL.createObjectURL(blob);
// trigger the download
downloader.click();
In my opinion, a redirect to the downloadable resource could be the best choice.

PDF file name not taken into account in IE10 / Edge

Using this code, i have the pdf's name that is incorrect : A string of random letters like a uuid.
This problem seems to only be with IE 10 / Edge.
AngularJS's version 1.4.7
this.downloadPdf = function(pdfName){
console.log(pdfName);
$http.get(config.UrlApi + "/pdf/"+ pdfName.nameFile, { responseType: 'arraybuffer' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.download = pdfName.name;
document.body.appendChild(a);
a.click();
});
Use the Blob Interface:
function build(response)
{
var bb = new Blob([response.data], { type: "application/pdf"});
if (URL && URL.hasOwnProperty("createObjectURL") )
{
var url = URL.createObjectURL(bb);
}
else if (window.navigator.msSaveOrOpenBlob)
{
window.navigator.msSaveOrOpenBlob(bb, 'foo.pdf');
}
}
$http.get(config.UrlApi + "/pdf/"+ pdfName.nameFile, { responseType: 'arraybuffer' }).then(build);
Blob urls are subject to an origin policy. This means that they can only be used in documents that have the same site-of-origin as the document running the script that created the url. If you need to use the blob object from an <iframe> that is running in a different domain, you must use the postMessage API to send the blob data to the frame and then create the blob: url there.
References
Saving files locally using Blob and msSaveBlob
New Blob Constructor in IE10
Edge Doesn't Use download attribute to set filename for blob URI downloading
Blob Object
URL.createObjectURL
MSDN: JavaScript Version Information

saving the cropped image - to amazon s3

I am cropping the image . But When I upload it to the amazon , it saves the originalfile.
function _handleFileSelect(evt) {
$scope.beforeLogoSelect = false;
$scope.file = evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function(evt) {
$scope.$apply(function($scope) {
$scope.myImage = evt.target.result;
});
};
reader.readAsDataURL($scope.file);
}
This way I get the url of the image and assign it to the cropped image tag.
Now How shal i save the cropped file to a file variable so that I can upload to amazon s3? I want the resultant cropped image in $scope.file.
Thanks.
Converting the data uri to blob was the solution.
Convert Data URI to File then append to FormData
Might be useful for others.

Resources