I have written the following code for download file from Google drive using JavaScript but I am not able to open file after completion of download its giving error like file format does not match my code as below,
function createPicker() {
var picker = new FilePicker({
apiKey: 'myapikey',
clientId: 'myclientID',
buttonEl: document.getElementById('ancggdgdgdd'),
onSelect: function (file) {
downloadFile(file);
}
});
}
and to read the content of file code as:
function downloadFile(doc) {
var myToken = gapi.auth.getToken();
var contentType = "text/plain;charset=utf-8";
var rawFile = new XMLHttpRequest();
rawFile.open("GET", doc.downloadUrl, false);
rawFile.setRequestHeader('Content-type', contentType)
rawFile.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
sendFile(rawFile.responseText);//here I am sending httpcontext
}
}
}
//rawFile.responseType = "arraybuffer";
rawFile.send(null);
}
Try this function for downloading the files:
/**
* Download a file's content.
*
* #param {File} file Drive File instance.
* #param {Function} callback Function to call when the request is complete.
*/
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
You can find more information in the following link: https://developers.google.com/drive/web/manage-downloads
Related
Hello Developers,
I'm trying to download the list of files getting form XMLHttpRequest() request method and store it in the array of files. I wanted to zip all the files in an array using javascript without using any 3rd party library.
I have tried to achieve this by URL.createObjectURL(url) and URL.revokeObjectURL(url) method but the file I'm getting is corrupted.
I'm Sharing my code snippet please help me out
const URLS = [
'https://vr.josh.earth/assets/2dimages/saturnv.jpg',
'https://vr.josh.earth/assets/360images/hotel_small.jpg',
'https://vr.josh.earth/assets/360images/redwoods.jpg'
];
$(document).ready(function () {
debugger
$("#downloadAll").click(function () {
var blob = new Array();
var files = new Array();
URLS.forEach(function (url, i) {
getRawData(url, function (err, data) {
debugger
var mydata = data;
// mydata = btoa(encodeURIComponent(data));
// var blobData = b64toBlob(mydata , 'image/jpg');
var blobData = new Blob([mydata], { type: 'image/jpg' });
blob.push(blobData);
var filename = "testFiles" + i + ".jpg";
var file = blobToFile(blobData, filename);
files.push(file);
debugger
if (files.length == URLS.length) {
// saveData(blob, "fileName.zip");
var AllBlobData = new Blob([blob], { type: 'application/zip' });
saveData(AllBlobData, "Test.zip");
// saveFile("DownloadFiles.zip", "application/zip", files)
}
});
});
});
});
//Retriving record using XMLHttpRequest() method.
function getRawData(urlPath, callback, progress) {
var request = new XMLHttpRequest();
request.open("GET", urlPath, true);
request.setRequestHeader('Accept', '');
if ('responseType' in request)
request.responseType = "arraybuffer"
if (request.overrideMimeType)
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send();
var file, err;
request.onreadystatechange = function () {
if (this.readyState === 4) {
request.onreadystatechange = null;
if (this.status === 200) {
try {
debugger
var file = request.response || request.responseText;
} catch (error) {
throw error;
}
callback(err, file);
} else {
debugger
callback(new Error("Ajax Error!!"))
}
} else {
debugger
}
}
}
//For Saving the file into zip
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
// var AllBlobs = new Blob([data], { type: "" });//application/zip //octet/stream
// var url = window.URL.createObjectURL(AllBlobs);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
//Downloaded Zip File
enter image description here
I use XMLHttpRequest to send POST data to nodejs (expressjs api). The size of file about 200mb. When I do, Chrome crashes, but the Firefox doesn't. Does Chrome have a limited file size?
And how can I upload the large file via JavaScript?
This is my code send xhr request:
// create http request API AI Engine
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.timeout = 3600000;
xhr.onload = function() {
// reponse measage
if (this.status === 200) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'none';
zip.files = {};
// unzip File
zip.loadAsync(this.response)
.then(function(zip) {
// will be called, even if content is corrupted
for (const file in zip.files) {
if (zip.files.hasOwnProperty(file)) {
const fileObject = zip.files[file];
fileObject.async('arraybuffer').then(function(fileData) {
var fileSave = new Blob([new Uint8Array(
fileData)]);
// Save file
saveAs(fileSave, fileObject.name);
})
}
}
}, function(e) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not unzip file return.';
});
// get response stream data
} else {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
}
};
// Handle when have error with xhr, show message
xhr.onerror = function(err) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
};
// Handle when have timeout with xhr, show message
xhr.ontimeout = function() {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: Request time out';
};
// Add custom header
xhr.setRequestHeader('Content-type', 'application/octet-stream');
xhr.setRequestHeader('file-name', Date.now().toString() + '.zip');
xhr.setRequestHeader('file-length', data.byteLength);
// Send arraybuffer to server
xhr.send(data);
});
I am able to implement the image upload example found in the documentation of TinyMCE:
https://www.tinymce.com/docs/advanced/php-upload-handler/
My question is how can I show the user a specific error message when an error occurs? For example, if I upload an invalid file type, it only shows a generic 500 error message like this:
How can I show a more specific error message to the user like
"Invalid extension"?
Hi need to write your custom images_upload_handler.
In settings add this lines :
images_upload_handler : function handler(blobInfo, success, failure, progress) {
{
var valid_extensions = ['png','jpg']
var ext, extensions;
extensions = {
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/gif': 'gif',
'image/png': 'png'
};
ext = extensions[blobInfo.blob().type.toLowerCase()] || 'dat';
//add your extension test here.
if( valid_extensions.indexOf(ext) == -1){
failure("Invalid extension");
return;
}
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.open('POST', settings.url);
xhr.withCredentials = settings.credentials;
xhr.upload.onprogress = function(e) {
progress(e.loaded / e.total * 100);
};
xhr.onerror = function() {
failure("Image upload failed due to a XHR Transport error. Code: " + xhr.status);
};
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure("HTTP Error: " + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != "string") {
failure("Invalid JSON: " + xhr.responseText);
return;
}
success(pathJoin(settings.basePath, json.location));
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
}
Im following this guide to use aJax to upload an image, mainly so I can have a progress bar. But for some reason the PHP script doesn't seem to receive a file!
Here is my JavaScript:
function submitFile() {
var form = document.forms.namedItem("imageUpload");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
console.log("uploaded!");
doc("imageResponse").innerHTML = xhr.responseText;
} else {
console.log("error!");
doc("imageResponse").innerHTML += "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
}
};
//Progress
/*
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100);
document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%";
}
};
*/
//Send data
xhr.send(formData);
}
And here is my PHP file which receives the file:
<?php
session_start();
print_r($_FILES);
?>
Currently that PHP file is returning an empty Array... it should have my file!
Array ( )
I managed to fix my code, here is the working version for anyone with the same problem. I decided to make a new form using JavaScript and append the file field value to this new form.
I did this mainly for my situation.
function submitFile(file,buttonId) {
//Generate a new form
var f = document.createElement("form");
f.setAttribute("method", "POST");
f.setAttribute("enctype", "multipart/form-data");
//Create FormData Object
var formData = new FormData(f);
//Append file
formData.append("image", file.files[0], "image.jpg");
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
document.getElementById(buttonId).innerHTML = "UPLOAD COMPLETE";
//console.log("uploaded!");
} else {
//console.log("error!");
alert("Error " + xhr.status + " occurred when trying to upload your file");
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
document.getElementById(buttonId).innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById(buttonId).style.backgroundSize = (currentPercentage+1) + "% 100%";
if (currentPercentage==99) {
document.getElementById(buttonId).innerHTML = "Processing image";
}
}
};
//Send data
xhr.send(formData);
}
I'm using the following code to upload file to the server,
Javascript:
function FileUpload(ServerName) {
alert("Entering File Change...");
var file = this.file1[0];
alert("File Change");
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function(e) {
alert("progress");
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if ( xhr.upload ) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', "http://localhost:49868/UploadFile/" + ServerName, true);
xhr.send(file);
}
Web api code:
[HttpPost]
[ActionName("UploadFile")]
public HttpResponseMessage UploadFile(string servername)
{
try
{
HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var httpRequest = HttpContext.Current.Request;
HttpResponseMessage result = null;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
//var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs("C:\\Users\\Desktop\\New folder (4)\\" + postedFile.FileName);
//files.Add(filePath);
//File.Copy(filePath, RootPath + postedFile.FileName);
//File.Delete(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
catch (Exception ex)
{
return null;
}
}
My Question is how to handle this on the server side, i.e in the web api, how to get the file there on the server and store it in some specific location?
Now the httpRequest.Files is returned null, where to get the file and save it?