I can upload the pdf file, but it will upload as blank/empty file. I don't know what am i missing from here.
Backend i receive the file, i also tried without converting to Base64 and still the same thing.
using (var sr = new StreamReader(file.OpenReadStream(), System.Text.Encoding.UTF8))
{
_fContent = await sr.ReadToEndAsync();
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_fContent);
_fContent = System.Convert.ToBase64String(plainTextBytes);
}
Frontend i create the request.
endpoint = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id';
method = 'POST';
_metadata = {
'name': fileName,
'mimeType': 'application/pdf',
'parents': [zzzz]
};
//blob is the data we receive in backend from _fContent variable
var file = new Blob([blob], { type: 'application/pdf' });
var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(_metadata)], { type: 'application/json' }));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open(method, endpoint);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
GapiUploadCallback(xhr.response, responseReturn);
};
xhr.send(form);
This is what i receive in google drive API, an empty/blank PDF file. Note: File size is
1 MB (1,424,457 bytes)
Using javascript FileReader was the only option i could solve this. PDF's are rendering ok on Google Drive now.
var fileUpload = $("#fileUpload").get(0);
var files = fileUpload.files;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var file = new Blob([dataURL], { type: 'application/pdf' });
var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(_metadata)], { type: 'application/json' }));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open(method, endpoint);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
GapiUploadCallback(xhr.response, responseReturn);
};
xhr.send(form);
};
reader.readAsArrayBuffer(files[0]);
Related
I'm wanting to get the contents of a mp3 file from a url get_mp3_file(mp3_file), then upload the contents of the mp3 I just downloaded, to another webserver and get the response.
var mp3_url = 'https://example.com/song.mp3';
function get_mp3_file(mp3_url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', mp3_url, false);
xhr.send();
return xhr.responseText;
}
var fd = new FormData();
fd.append("file", get_mp3_file(mp3_url));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://mp3-to-wav.com/upload-file.php', false);
xhr.send(fd);
var wav_link = JSON.parse(xhr.responseText).link;
the key was the File class. here's more about it.
https://w3c.github.io/FileAPI/#file-constructor
The solution for retrieving the contents of a file from one webserver, and then uploading it to another webserver:
var mp3_url = 'https://example.com/song.mp3';
var xhr = new XMLHttpRequest();
xhr.open('GET', mp3_url, false);
xhr.responseType = 'blob';
xhr.onload = function() {
var xhr2 = new XMLHttpRequest();
var file = new File([xhr.response], 'song.mp3', {type: 'audio/mp3'});
var formData = new FormData();
formData.append('file', file);
xhr2.open('POST', "https://convert-mp3-to-wav.com", false);
xhr2.send(formData);
}
xhr.send();
So, To download images/pdf that have blob: url in wkwebview, i injected javascript to my code.Here's the javaScript:
function(url) {
function blobToBase64String(blob, callback) {
var reader = new FileReader();
reader.onloadend = function() {
callback(this.result.split(",")[1]);
};
reader.readAsDataURL(blob);
}
if (url.startsWith("blob:")) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status !== 200) {
return;
}
var blob = this.response;
blobToBase64String(blob, function(base64String) {
webkit.messageHandlers.downloadManager.postMessage({
url: url,
mimeType: blob.type,
size: blob.size,
base64String: base64String
});
});
};
xhr.send();
return;
}
var link = document.createElement("a");
link.href = url;
link.dispatchEvent(new MouseEvent("click"));}
This is the error i m getting:
XMLHttpRequest cannot load blob:https://url due to access control checks.
Is there any way to allow request in wkwebview. I m not sure, where to head forward! Is there any preferences in wkwebview, that needs to be enabled?
I have Java REST webservice that returns documents as byte array, I need to write JavaScript code to get the webservice's response and write it to a file in order to download that file as PDF Kindly see a screen shot of the webservice's response and see my sample code this code downloads a corrupted PDF file.
var data = new FormData();
data.append('PARAM1', 'Value1');
data.append('PARAM2', 'Value2');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SERVICEURL');
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
xhr.onload = function() {
console.log('Response text = ' + xhr.responseText);
console.log('Returned status = ' + xhr.status);
var arr = [];
arr.push(xhr.responseText);
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(byteArray, { type: 'application/octet-stream' }));
a.download = "tst.pdf";
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
};
xhr.send(data);
Since you are requesting a binary file you need to tell XHR about that otherwise it will use the default "text" (UTF-8) encoding that will interpret pdf as text and will mess up the encoding. Just assign responseType property a value of 'blob' or the MIME type of pdf
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file
// OR xhr.responseType = 'application/pdf'; if above doesn't work
And you will access it using response property and not responseText.
So you will use arr.push(xhr.response); and it will return you a Blob.
If this doesn't work, inform me will update another solution.
Update:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file
xhr.onload = function() {
var blob = this.response;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = "tst.pdf";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
I need to download a file that has been uploaded to Firebase Storage. I used to get the CORS error but I used gsutil as per the docs and now nothing really happens. The download doesn't start. What am I doing wrong?
//Create reference of Storage
let storage = firebase.storage();
//Create reference to file in Storage
let pathSubmission = 'Uploads/' + this.place1+ '/' + this.place2+ '/' + this.place3+ '/' + this.downloadSubmissionUID;
let storageRef = storage.ref(pathSubmission);
storageRef.getDownloadURL().then((url) => {
console.log('downloadURL arg: ' + url);
//Download file (no idea how this works)
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
})
Figured it out using Kai's blog, here's my solution:
//Create reference of Storage
let storage = firebase.storage();
//Create reference to file in Storage
let pathSubmission = 'Uploads/' + this.place1 + '/' + this.place2+ '/' + this.place3 + '/' + this.downloadSubmissionUID;
//Assign Storage reference the path reference
let storageRef = storage.ref(pathSubmission);
//Download file by creating XMLHttpRequest
storageRef.getDownloadURL().then((url) => {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
//Create an `a` tag (since it has an `href` and a `download` attribute)
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = 'someFileName';
a.style.display = 'none';
document.body.appendChild(a);
a.click(); //Simulates a click event
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
})
Actually, the file is probably getting downloaded. The problem is in this code here:
//Download file (no idea how this works)
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
The browser is doing exactly what it's told. It downloads the file as a blob. Then discards the result, because you aren't doing anything with the data in the onload handler!
First, I'd recommend using fetch, which provides a much more intuitive API than the XMLHttpRequest (in my opinion).
Here's how you might do that:
// Create reference of Storage
let storage = firebase.storage();
// Create reference to file in Storage
let pathSubmission = 'Uploads/' + this.place1+ '/' + this.place2+ '/' + this.place3+ '/' + this.downloadSubmissionUID;
let storageRef = storage.ref(pathSubmission);
storageRef.getDownloadURL()
.then(url => {
console.log('Download URL: ' + url)
return fetch(url)
})
.then(response => response.blob())
.then(blob => {
console.log('File downloaded as blob')
// Do something with the blob...
})
.catch(error => {
console.error('Something went wrong while downloading the file:', error)
})
I am able to fetch the contents of a zip file from google drive using javascript api. But i am not able to unzip the file. I am using JSZip (http://stuartk.com/jszip) to unzip. How do i achive this. Please help i am stuck on this from last 3 days.
gapi.client.load('drive', 'v2', function(){
var config = {
'client_id': '{!gApp.clientid__c}',
'scope': 'https://www.googleapis.com/auth/drive',
'immediate':true
};
gapi.auth.authorize(config, function() {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', fileURL);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
//reponse :unzip the file here
var zipData = xhr.responseText;
var zip = new JSZip(zipData, {base64:false});
console.log(zip.files) //get an error undefined
};
xhr.onerror = function() {
alert('error');
};
xhr.send();
});
});