There are a lot of questions about file upload with Android but most of them without answer and actually none of them are related with javascript or php.
I'm seeing strange behaviour when selecting a file to upload on Android (4.4.4) native browser (HTC One_M8) and what it gives me is this;
C:\fakepath\image:12045
"Fakepath" part doesnt bother me, what bothers me is that I cant get file name out of /input type="file"/ html tag.
I'm sending files with $.ajax and it works on Chrome, FF, Safari (desktop & iPhone), It works also on my M8 with Chrome, but not with native browser.
This is what I use to get selected files;
var filedata = document.getElementById("userFile");
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
// showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("userFile[]", file);
}
}
And this is how I send them to handle.php
$.ajax({
url: 'handle.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
}
return myXhr;
},
data: formdata,
dataType:'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr, opt) {
$('#control-console').append($('input[type=file]').val());
$('input[type=file]').val("");
},
success: function() {
},
complete: function(podatki) {
$('#control-console').append(podatki.responseJSON.name);
console.log(podatki)
$.each(podatki.responseJSON.name, function(i, val) {
console.log(val);
insertFrame(val);
});
processing = false;
}
});
I haven't found any documentation about this so I don't really know if this is a bug in Android native browser or do I have to use different approach.
Has anyone faced the same problem and maybe found a solution ?
I have researched a lot and i have made a solution for android only. When you are in browser and iPhone, you can use your solution as it is working perfectly. But, android have a security issue. So, i had to make a solution for android.
You can follow my solution here.
What I have researched in last few hours is when file being uploaded is within the gallery for the android phone, due to security checks above problem happens. No file name, extension, size will be readable.
To workaround this:
1- Click on browse button, you will be taken to gallery of your device.
2- On right corner of gallery click Options image ("...") and Enable "Internal Storage".
3- Make sure the file you upload is in Internal Storage.
4- Access "Internal Storage" option while uploading.
5- File should show the correct name.
Related
I'm trying to integrate Chen Fengyuan's 'cropperjs' into a website I'm designing and I have the interface working fine with the crop box doing as it should. However, my limited knowledge of Javascript and jQuery has brought me to a standstill.
What I would like to do is click on a button under the canvas (similar to the Get Cropped Canvas button) and have the cropped image posted to the server using a simple jQuery AJAX call.
I don’t need a preview of the cropped image as the image is already previewed on the interface. However, I can't seem to do this successfully because every time I try and use the methods provided in the 'cropperjs' documentation, I get a browser errors like:
ReferenceError: cropper is not defined
I've tried various methods and have seen a lot of solutions online but I just can't seem to get it right. I know I'm doing something very wrong but because I don't understand Javascript and jQuery well enough. I'm really struggling. The documentation mentions initialising with the Cropper constructor but I don't know how to do this and I'm guessing this is where my problem is? Can anyone help?
I've manage to painfully solve this myself so for anyone who's interested, here's the code I used:-
var $image = $("#image");
var cropper = $image.cropper();
var baseURL = window.location.protocol+'//'+window.location.host;
var pho_id = $("input[name=pho_id]").val();
var mem_id = $("input[name=mem_id]").val();
var photopath = $("input[name=photopath]").val();
$image.cropper('getCroppedCanvas').toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
formData.append('pho_id', pho_id);
formData.append('mem_id', mem_id);
formData.append('photopath', photopath);
$.ajax(baseURL+'/path/', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
}, 'image/jpeg', 0.8);
We are currently uploading a photo to a WebMethod via javascript everything works perfectly fine on local.
Yet when I deploy this to staging we get the following exception: System.IO.FileNotFoundException Our javascript method is as follows:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]); // Image
formData.append('c', i);
formData.append('t', t);
formData.append('i', uuid);
$.ajax({
url: "/member/myserice/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
alert('success');
},
error: function (er) {
alert('Unable to upload photo at this time, please try again later');
}
});
Now as you can see we store the uploaded image inside formData (first parameter)
Our WebMethod is as follows:
public string UploadImage()
{
var httpRequest = HttpContext.Current.Request;
var timestamp = httpRequest.Form["t"];
var consumerId = httpRequest.Form["c"];
var guid = httpRequest.Form["i"];
var pic = System.Web.HttpContext.Current.Request.Files["file"];
string fileName = Path.GetFileName(pic.FileName); // Breaks here when deployed to staging
var img = System.Drawing.Image.FromFile(pic.FileName);
//Removed additional code as it calls an external API.
}
Now as mentioned before this works perfectly fine on local, yet when deployed to staging I get the exception System.IO.FileNotFoundException on the following line:
string fileName = Path.GetFileName(pic.FileName);
Now I've tried searching the web for a given solution or an detailed explanation into why and how to fix but with no avail, can someone shed some light into what if needs be I need change to get this to function correctly.
Thanks in advance.
This works locally because both client and server use the same file system and path from $('#photo')[0].files[0] point to same file on server. You shouldn't try to read file from file system on server side, but use the file stream from HttpContext
Instead of
var pic = System.Web.HttpContext.Current.Request.Files["file"];
string fileName = Path.GetFileName(pic.FileName); // Breaks here when deployed to staging
var img = System.Drawing.Image.FromFile(pic.FileName);
Use the file stream uploaded from client:
var pic = System.Web.HttpContext.Current.Request.Files["file"];
var img = System.Drawing.Image.FromStream(pic.InputStream);
using webkitRequestFileSystem, I want to do something very simple: get a file from user, save it to browser local filesystem, and use it later (for example as image src etc)
I read about webkitRequestFileSystem but I didn't find anything about cloning files from user (maybe I missed it?).
so I tried a naive implementation of reading, getting file, writing, and everything seems to works (calls the success callback), and I can see the file with a chrome extension (HTML5 filesystem explorer), but when I try to use the image url it shows a broken image icon.
here's the snippet to clone the file (sort-of, had to clean it up a little):
var src_file = .... <-- got it from user
filesystem.root.getFile("output.png", {create: true}, function(dest_file)
{
var reader = new FileReader();
reader.onerror = function() {alert("ERROR")};
reader.onload = function(e)
{
read_buffer = e.target;
dest_file.createWriter(function(fileWriter) {
var blob = new Blob([read_buffer.result], {type: 'application/octet-stream'}); // <-- also tried "image/png" etc..
fileWriter.onerror = function() {alert("ERROR2")};
fileWriter.onwriteend = function(writer)
{
alert("SUCCESS!");
};
fileWriter.write(blob);
}, function() {alert("ERROR3")});
};
reader.readAsBinaryString(src_file);
});
PS I work on localhost, is that an issue?
Thanks!
answering myself: should have used readAsArrayBuffer() instead of readAsBinaryString()... what a waste of time that was :/
I'm using file api and xhr2 spec. I created an uploader (backed by flash for older browsers) that was using FormData and $.ajax(options) where the FormData object with File was part of options.data object. Everything was working.
Now I decided to remove FormData because of weak browser support. And I can't figure a way to upload the file other than
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(file);
Which doesn't return Promise that I can use in the recursion function.
My code is like this :
startUpload: function() {
var that = this;
that.recurseSend(that.queue);
},
_initProgressListener: function (options, file) {
var that = this;
var xhr = $.ajaxSettings.xhr();
options.contentType = 'multipart/form-data';
options.processData = false;
options.type = 'POST';
// WHAT TO DO HERE TO avoid FormData???? What ever I put into options.data - fails
/* THIS WOULD WORK
var formData = new FormData();
formData.append('file', file);
options.data = formData;
*/
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener('progress', function (e) {
that._onProgress(e, file);
}, false);
options.xhr = function () {
return xhr;
};
}
},
recurseSend: function (queue) {
var file = queue.pop();
if(file != undefined) {
var that = this;
var options = that.options;
that._initProgressListener(options, file);
var send = function() {
jqXHR = ($.ajax(options)).done(function(result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, file);
queue.stats['successful_uploads']++;
}).fail(function(jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, file);
queue.stats['upload_errors']++;
}).always(function(result, textStatus, jqXHR) {
that._onAlways(result, textStatus, jqXHR, file);
queue.stats['files_queued']--;
that.recurseSend(queue);
});
return jqXHR;
};
this._beforeSend(file);
return send();
}
},
To make it short, $.ajax(options) resolves into xhr.send(formData) if options.data = FormData but how do I make it resolve into xhr.send(file) ?
EDITED: I was playing with it and if I set options.data = file; then $.ajax(options) executes xhr.send(theFile); but with error Error: INVALID_STATE_ERR: DOM Exception 11
and the request is sent as POST multipart/form-data request, but without the multipart body with file in it
And if I put it into options.data = {file: file}; it is serialized no matter if processData property is set to true or not.
You can manually generate the MIME data for the upload from the HTML5 file data read using FileReader or similar APIs. Check out: https://github.com/coolaj86/html5-formdata . This will do more or less that, although it depends on getAsBinary() -- changing it to also be able to use FileReader and readAsBinaryString() would probably be more cross-browser-compatible.
Note that this still won't work at all in IE7/8, and as others have said, there is no way to do it without resorting to Flash or iframes. That being said, if you're using File, presumably you don't care about IE7 or IE8 anyway...
Whenever you are dealing with uploading arbitrary data from a users machine, the answer is usually "no, and if you can, that's a bug".
This strikes me as something that would fall under the umbrella of security violations. You can't change the value of the file input control or do many other things to it including read the true path of the file or its contents. Furthermore, on some platforms you don't have even the file size (IE, I'm looking at you) without some security dialog popping up (via an activex control). Given all of these problems I would probably be tempted to say that even if you did find a solution, it would be potentially viewed as a bug in the future and removed or changed.
In other words, I don't think it's a safe thing to do unless you find a reputable source explicitly supporting it ... like the chromium dev blog.
I my self have used valums ajax uploader. You can get it from here:
http://valums.com/ajax-upload/. It works pretty nicely. I don't know the exact implementation details, but here's a very short description:
"This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere."
So it sounds like its very close to what you want. Here's another bit of info describing the way it works from the servers point of view (from server/readme.txt):
For IE6-8, Opera, older versions of other browsers you get the file as
you normally do with regular form-base uploads.
For browsers which upload file with progress bar, you will need to get the raw
post data and write it to the file.
So it requires special handling on the server side. Luckily it comes with several reference server side implementations (perl, php and java) so that shouldn't be too much of hassle. Happy ajax uploading :)
How can I upload files asynchronously?
It seems you can't do this without going through an iFrame. There seem to be working snippets in the answer i linked, and several plugins that do it for you.
* edit since I am getting comments on it *
Yes it is possible- http://caniuse.com/xhr2 - theres no IE support below 10 though..
Heres a tutorial:
http://www.html5rocks.com/en/tutorials/file/xhr2/
http://www.profilepicture.co.uk/ajax-file-upload-xmlhttprequest-level-2/
Working with HTML5's File API, the upload is made via an object called upload in the XMLHttpRequest. This is the tutorial I'm working with (and the Google cache mirror since it's down at the moment). This is the relevant part:
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
As you can see, to track the upload progress, the XMLHttpRequest object has a property named upload, which we can add an event handler.
My question is: has jQuery an equivalent?. I'm attempting to leave the code as clean as and cross-browser compatible as possible, for whenever Microsoft thinks it's a good idea (although it sounds like it will be in 2012 or 2013).
Here is what I came up with to get around the issue. The $.ajax() call allows to provide a callback to generate the XHR. I just generate one before calling the request, set it up and then create a closure to return it when $.ajax() will need it. It would have been much easier if they just gave access to it through jqxhr, but they don't.
var reader = new FileReader();
reader.onloadend = function (e) {
var xhr, provider;
xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
// ...
}, false);
}
provider = function () {
return xhr;
};
// Leave only the actual base64 component of the 'URL'
// Sending as binary ends up mangling the data somehow
// base64_decode() on the PHP side will return the valid file.
var data = e.target.result;
data = data.substr(data.indexOf('base64') + 7);
$.ajax({
type: 'POST',
url: 'http://example.com/upload.php',
xhr: provider,
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
},
data: {
name: file.name,
size: file.size,
type: file.type,
data: data,
}
});
};
reader.readAsDataURL(file);
The documentation for the jqXHR (the superset of the XMLHttpRequest that is returned from jQuery's .ajax() call) does not describe the update feature as being exposed, which does not mean it isn't exposed. This question, though, seems to indicate that upload is not exposed. The answer provides a way to get to the native XMLHttpRequest object.
In versions before jQuery 1.5 the XMLHttpRequest object was exposed directly, and so you can access any feature of it that the browser supports. This tutorial for building a drag and drop uploader does just that.
A search for jquery html 5 file upload brings up this plugin to do multiple file upload using the HTML 5 file API, but this plugin does not currently work in IE. If you don't want to use HTML 5 and instead do want to have support cross-browser now, there are other plugins you can look into for jQuery on the jQuery plugin site.