Append formdata for multiple file upload [duplicate] - javascript

I need to upload files using ajax which has to be supported in IE9. I was using FormData as mentioned here. My code looks like this:
var files = new FormData();
JQuery.each($('#file')[0].files, function (i, file) {
files.append('file', file);
});
$.ajax({
type: "POST",
url: '/url',
cache: false,
contentType: false,
processData: false,
data: files,
...
});
This works fine in Safari and Firefox, but fails in IE9 as the FormData is not supported in IE9. I tried sending just as a file by setting:
data: $('#file')[0].files[0]
contentType: 'multipart/form-data'
This fails as the data is sent in url-encoded form and is cannot be parsed at the java side. Any help or pointer on how to solve this will be greatly appreciated. I need something that works across all browsers.
EDIT: I do not need any upload progress bar as the files are usually small. I do not need to upload multiple files. I just need a single file upload.

Unfortunately you cannot use Ajax (XMLHttpRequest in other words) for sending files, but you can implement a similar behavior using the <iframe/> with a <form method="post" enctype="multipart/form-data"/> that contains an <input type="file"/> which sends a user chosen file using the "natural" way. You can use javascript to call the form.submit() then poll that <iframe/> from parent document to check whether the file upload process is done.
jQuery has a lot of cool plugins for getting this job done, there is my favorite one, for example.

Related

Blueimp File Upload - Multiple Uploads Directly to S3

After searching the past couple days, I've found nearly 30 different people asking this same question, and I haven't found an answer. A couple reported that they found a solution, but did not provide it, so I'm hoping someone could answer it here.
Using blueimp jQuery File Upload, how can you upload multiple files directly to Amazon S3?
Problem: S3 accepts only one file per request.
Solution: Use blueimp jQuery File Upload to send separate requests for each file.
Roadblock: I cannot figure out how to make blueimp jQuery File Upload do this.
Solution Attempt
The guide is here: https://github.com/blueimp/jQuery-File-Upload/wiki/Upload-directly-to-S3
S3 currently requires more form fields than the ones shown in the guide. Here's a trimmed down version of my code:
$(':file').each(function(i, el) {
var fileInput = $(el);
var form = fileInput.parents('form:first');
fileInput.fileupload({
forceIframeTransport: true,
autoUpload: true,
singleFileUploads: true, //default anyway
add: function(event, data) {
var files = data.files || [];
var nextInQueue = files[0]; //this is a queue, not a list
console.log('nextInQueue:', nextInQueue);
if (!nextInQueue) return;
var fileData = {name: nextInQueue.name, mime: nextInQueue.type, size: nextInQueue.size};
$.ajax({
url: '/s3stuff',
type: 'POST',
dataType: 'json',
data: {'file': fileData},
async: false,
success: function(res) {
form.find('input[name="key"]').val(res.key);
form.find('input[name="AWSAccessKeyId"]').val(res.AWSAccessKeyId);
form.find('input[name="policy"]').val(res.policy);
form.find('input[name="signature"]').val(res.signature);
form.find('input[name="acl"]').val(res.acl);
form.find('input[name="success_action_status"]').val(res.success_action_status);
form.find('input[name="Content-Type"]').val(nextInQueue.type);
form.attr('action', res.url);
data.submit(); //why is this submitting all files at once?
}
});
},
fail: function(err) {
console.log('err:', err.stack);
}
});
});
Error
When I try to upload a single file, it works great! But when I try to upload multiple files, S3 returns this 400 error:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InvalidArgument</Code>
<Message>POST requires exactly one file upload per request.</Message>
<ArgumentName>file</ArgumentName>
<ArgumentValue>2</ArgumentValue>
</Error>
Analysis
The blueimp jQuery File Upload documentation says this (under add):
If the singleFileUploads option is enabled (which is the default), the add callback will be called once for each file in the selection for XHR file uploads, with a data.files array length of one, as each file is uploaded individually.
This is where I'm stuck:
If "each file is uploaded individually" to S3, why does S3 say otherwise?
Also, regardless of the number of files, the add function runs only once. (I verify this with the console.log statement.) I see 2 likely reasons for this:
The plugin stops further submissions after one fails.
The plugin is not submitting files individually (for whatever reason).
Is my code incorrect, am I missing an option in the plugin, or does the plugin not support multiple direct uploads to S3?
Update
Here's an html file for quick testing:
http://pastebin.com/mUBgr4MP
Author of JQuery File Upload here.
The reason the files are not submitted individually is the forceIframeTransport option, which is set to true in your example.
The documentation for the singleFileUploads option states the following:
By default, each file of a selection is uploaded using an individual request for XHR type uploads.
While the documentation for the forceIframeTransport option states the following:
Set this option to true to force iframe transport uploads, even if the browser is capable of XHR file uploads.
So, the solution is to enable CORS on the S3 bucket and to not enable the forceIframeTransport option.
By the way, most of the integration examples are user contributions (including the S3 upload guides).
Here's another one which uses the S3 CORS feature and might help your out (haven't tested it though):
http://pjambet.github.io/blog/direct-upload-to-s3

How to upload an image file using only javascript and ajax

In form, There is a field of file
<input type="file" name="file">
<input type="button" value="upload">
I want to upload image file onto server but I can't able to upload the image. Is there any solution in only javascript? Please help me to find this answer.
Thanks..!
This isn't possible with JavaScript alone, you will need to use a server side language to process the actual uploading of the file.
This will do the job in Firefox, IE does not support FormData, so you should find another way
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<form id="data">
<fieldset>
<div>Asset File: <input id="image_file" name="image_file[]" type="file" /></div>
<div><input type="submit" value="Submit"></div>
</fieldset>
</form>
<script>
$(function() {
$("form#data").submit(function(event){
event.preventDefault();
var url = 'http://server.com/upload';
var image_file = $('#image_file').get(0).files[0];
var formData = new FormData();
formData.append("image_file", image_file);
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (status) {
// do something on success
}
});
return false;
});
});
</script>
Your web site files are stored at the server. JavaScript runs at the client-side.
The images must be stored somewhere. But the client-side JavaScript have access to the user's browser window (or tab). and user's cache. You cannot write files at the server storage using only client-side JavaScript.
The ways images are uploaded and downloaded:
Download:
You send request to the server using JavaScript (ajax for example). In this request you say: "GET http://my-site/images/cool-dog.png" This is static request that try to access images/cool-dog.png from your public folder on the server. Every server has option that allows you to determinate which folder will contain all the files for the static requests.
STATIC request is when you try to access a file with an extension (cool-dog.png)
Upload:
As we know, everybody can write client-side JavaScript to the console: Every major browser has debugging tools. And everybody can send any kind of request to your server from Postman for example.
It will be bad to accept all of there request. Somebody may want to upload 100GB file at max speed. That may affect the application and server performance or even hack the application.
You need server-side logic to determinate which file is good for your server and where this file must be stored, since the JavaScript know only about client-side storage (cookies, localStorage, sessionStorage, cache, etc...).
Upload process is:
You send request from the client-side JavaScript to the server-side. For example : POST http://my-site/uploadImage with the image data.
The server-side accepts that request. For example: Router.get('uploadImage', function() {...Server side code...}). Since http://my-site/uploadImage is dynamic path (we do not have extension) The server-side Router will wait for this kind request and if it's requested the server-side code must check the file size and extension (.png or .dll) and etc... And if the file is good for your application then you can write this file to the server location.
The different server languages and technologies has different methods for processing requests and writing files.
If you want to extend your knowledge you need to learn at least one server-side language and technology. You cannot make flexible applications only with client-side logic.
If you are familiar with JavaScript yet. You may want to learn NodeJS. This site contains great tutorials for NodeJS beginners.
PHP is also easy to learn if you can found some good tutorials.
Here is tutorial how to upload files using nodeJS
and here is another for PHP

Ajax put to add XML entries into XML file

I am trying to add some emails taken from an inputbox into a .txt file present on my webserver. Here is the code :
email = document.getElementById("mail").value;
$.ajax({
url: 'maillist.txt',
datatype: 'text',
type: 'PUT',
data: email + '; ',
success: function(data) {
alert('Should have work yay!');
}
});
but that doesn't work on any browser. :(
I have tried using javascript classic methods but it was a no go as well...
I would need either a PUT or POST method, either jQuery or JS, to be able to do this on internet explorer 8 and up as well as firefox and chrome. Emails should appear in the text file as
email1#cooldomain.com; email2#cooldomain.com; .....
Just so it works with our in-house VBA Macro. :)
Also, could there be a method for dropping data into XML files (aka create a new XML entry with form data)? And also, is it possible to upload a file from client side to server side using jQuery? Because i would need users to fill up forms and drop their data into an XML file, and link up a file they choose with that. That way they could add stuff into the XML themselves and they would show up brand new into the webpage.
Kindoff "reddit" or "4chan" like if you know the references.
Thanks for your time, really appreciated!
You can't post from a browser to a text file on the server side. You need to have some sort of code on the server side that will receive the HTTP PUT, and persist the data to a file local to the server.

How to save an image via JavaScript

I want to download a image file (jpeg image) to the user files system when user selects a photo and clicks a button. So far I searched and found this link and also this
I saw in one blog that downloadify when used with jszip can enable this feature but it didn't specify any farther on this. Does any one know how to download the images. I have the links to the images and i just want the user to download it on his system rather than again query the server.
Can anyone provide me with an example please.
Use the HTML5 download attribute.
As a choice you can set filename as an attribute value.
<a href="/images/image-name.jpg" download="new-image-name.jpg">
You can load the image in an canvas element get the data url of the canvas and open a new window with the data url as source. Take a look at this example: https://gist.github.com/1875132
Finally I did it. For anyone who may need this in the future here is how I did it using jquery
jQuery.ajax({
url: 'http://localhost:8080/yourwebsite/servlet?img=' + document.getElementById(id).alt,
//data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
// success: function() { alert("Success"); },
// error: function() { alert('Failed!'); },
// beforeSend: setHeader
});
this I had to do come across the problem of cross domain http requests which are usually blocked by most websites unless you follow some lengthy process. So, I made it simpler and called a get method in my servlet and passed it the url of the image from which it downloaded the image.This is much easier to do and even easier then this if you are on the same domain but that didn't meet my requirements and this code worked for me :)

Unable to parse file with jQuery in IE 8 and below because it's not XML (even though it sort of is XML)

I'm using AJAX to load in a KML file (which is basically an XML file). I'm able to parse everything fine in IE9, FF, etc., but in IE8 it doesn't work. I get the data back but I'm not able to parse it in jQuery. I'm assuming this is because it's not being acknowledged as true XML.
If I change the file from us_states.kml to us_states.xml, for example, it works fine.
So, I COULD try to have people change their files from kml to xml manually, but I'd prefer being able to read it in and have it work on all browsers, old and new.
Here is my ajax call:
$.ajax({
url: KMLFile,
type: "GET",
dataType: "XML",
success: function(data){ ...}
});
Thanks in advance for your help.
I'd skip the XML/KML issue completely and go straight to JSON:
http://code.google.com/p/geoxml3/wiki/JsonObjects

Categories