Uploading multiple files from different inputs using Ajax - javascript

I have two different file inputs and multiple textual/select inputs, that I'd like to upload to a PHP file using Ajax. The file inputs are meant to send images, and because they are two specific images that I'd like to identify by the name of the input, I do not want to use <input type="file" multiple>.
Currently I have the following (names have been changed to keep it simple):
<input type="file" name="file1">
<input type="file" name="file2">
<textarea name="text1"></textarea>
<button>Submit</button>
What I have tried is to push both to a variable once the change event of the file input gets fired, followed by the button press triggering the upload using Ajax.
$('input[type="file"][name="file1"]').on('change', prepareUpload);
$('input[type="file"][name="file2"]').on('change', prepareUpload);
files = new Array;
function prepareUpload(event){
files.push(event.target.files);
}
$('button').on('click', uploadFiles);
function uploadFiles(event){
$('#uploadInfo').html('Uploading...');
event.stopPropagation();
event.preventDefault();
var data = new FormData();
$.each(files, function(key, value){
data.append(key, value);
});
data.append('text1', $('textarea[name="text1"]').val());
$.ajax({
url: '',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
//do stuff
},
error: function(error){
console.log(error);
}
});
}
But this seems to do nothing. Is it even possible to append two image inputs to the same request using Ajax, or am I better off trying to put it in two different requests?

event.target.files is a array, so you need the first file in the array
function prepareUpload(event){
files.push(event.target.files[0]);
}

Related

How to receive a file and an integer sent through an ajax request in action method using asp.net core

I want to send an image and a number when the user perform an upload.
My Javascript
form.append('file', $(uploader).get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
$.ajax({
method: 'POST',
url: '/images/send',
data: form,
form: false,
processData: false
});
In my action what should I do?
With this I only receive the image.
[HttpPost]
public string send(IFormFile file) // What argument should I use
{
How do I get the number and file?
}
You can add a new parameter of type int to your action method. The parameter name should match with the formdata item name you are sending (id)
[HttpPost]
public string send(IFormFile file,int id)
{
// to do : return something.
}
You need to have the contentType property on your $.ajax method set to false
This should work.
var form = new FormData();
form.append('file', $('#File').get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
var urlToPost ="/images/send";
$.ajax({
method: 'POST',
url: urlToPost ,
data: form,
processData: false,
contentType: false
}).done(function(result) {
// do something with the result now
console.log(result);
}).fail(function(a, b, c) {
alert("error");
});
If you want to send multiple input values with the file input, i suggest you create a view model and use that as explained in this post.
Also it might be a good idea to keep your form elements inside a form and set it's action value to the url you want to send and read that in your javascript code that hard coding it there.
<form asp-action="send" asp-controller="images" method="post">
<input type="file" name="File" id="File" />
<input type="text" id="id" value="0" />
<input type="submit" />
</form>
Now in your javascript you can read it from the form. For example, if you are wiring up the submit event of the form
$(function () {
$("form").submit(function (e) {
e.preventDefault();
var urlToPost = $(this).attr("action");
//your existing code for ajax call
});
});

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

Multiple file upload with ajax and php

I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you!
Here is the code:
HTML:
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>
JavaScript:
$(document).ready(function(){
$("#file").change(function(){
var src=$("#file").val();
if(src!="")
{
formdata= new FormData(); // initialize formdata
var numfiles=this.files.length; // number of files
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/)) // Verify image file or not
{
if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
{
var reader = new FileReader(); // initialize filereader
reader.readAsDataURL(file); // read image file to display before upload
$("#preview").show();
$('#preview').html("");
reader.onloadend = function(e){
var image = $('<img>').attr('src',e.target.result);
$(image).appendTo('#preview');
};
formdata.append("file[]", file); // adding file to formdata
console.log(formdata);
if(i==(numfiles-1))
{
$("#info").html("wait a moment to complete upload");
$.ajax({
url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res){
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
});
And in PHP I get $_POST and $_FILES as an empty array;
Only if I do file_get_contents("php://input"); I get something like
-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png
PNG
���
IHDR��Ò��¾���gǺ¨��� pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö
But I can't figure out how to proceed from here.
I am using Jquery 1.3.2 maybe this is the problem?
Thank you!
Sorry about the answer, but I can't add a comment yet.
I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.
e.g.
This answer taken from another question (uploaded file type check by PHP), gives you an idea:
https://stackoverflow.com/a/6755263/1720515
<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>
You can read the documentation on the exif_imagetype() function here.
Could you post your PHP code please? And I will update my answer if I have anything to add.
UPDATE:
NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.
e.g.
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file_0" name="img_file[]" />
<input type="file" id="file_1" name="img_file[]" />
<input type="file" id="file_2" name="img_file[]" />
</form>
When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:
e.g.
$_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
$_FILES['img_file']['name'][0] - contains the file name including the file extension.
$_FILES['img_file']['size'][0] - contains the file size.
$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)
The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.
Here is some example code:
<?php
if (!empty($_FILES)) {
foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
/*
...perform checks on file here
e.g. Check file size is within your desired limits,
Check file type is an image before proceeding, etc.
*/
$permanent_filename = $_FILES['img_file']['name'][$file_key];
if (#move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
// Successful upload
} else {
// Catch any errors
}
}
}
?>
Here are some links that may help with your understanding:
http://www.w3schools.com/php/php_file_upload.asp
http://php.net/manual/en/features.file-upload.multiple.php
http://www.sitepoint.com/handle-file-uploads-php/
Plus, some extra reading concerning the theory around securing file upload vulnerabilities:
http://en.wikibooks.org/wiki/Web_Application_Security_Guide/File_upload_vulnerabilities
You can use ajax form upload plugin
That's what i have found couple of days ago and implemented it this way
Ref : LINK
You PHP Code can be like this
uploadimage.php
$response = array();
foreach ($_FILES as $file) {
/* Function for moving file to a location and get it's URL */
$response[] = FileUploader::uploadImage($file);
}
echo json_encode($response);
JS Code
options = {
beforeSend: function()
{
// Do some image loading
},
uploadProgress: function(event, position, total, percentComplete)
{
// Do some upload progresss
},
success: function()
{
// After Success
},
complete: function(response)
{
// Stop Loading
},
error: function()
{
}
};
$("#form").ajaxForm(options);
Now you can call any AJAX and submit your form.
You should consider below code
HTML
<input type="file" name="fileUpload" multiple>
AJAX
first of all you have to get all the files which you choose in "input type file" like this.
var file_data = $('input[type="file"]')[0].files;
var form_data = new FormData();
for(var i=0;i<file_data.length;i++)
{
form_data.append(file_data[i]['name'], file_data[i]);
}
then all your data is in formData object now you can send it to server(php) like this.
$.ajax({
url: 'upload.php', //your php action page name
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
// code you want to execute on success of ajax request
},
error: function (result) {
//code you want to execute on failure of ajax request
}
});
PHP
<?php
foreach($_FILES as $key=>$value)
{
move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
}

Uploaded file only contains "WebKitFormBoundary"

I don't really know what's going on here. Every time I try to upload a file, all the file contains is:
------WebKitFormBoundaryJ0uWMNv89fcUsC1t--
I have searched for the past 2 days for some sort of explanation, but I am just going in circles. I have no idea why this is happening.
Form:
<form id="upload-file" ecntype="multipart/form-data">
<input name="picture" type="file">
<input type="button" value="Upload" id="upload-button" />
</form>
Javascript:
$('#upload-button').click(function(e){
e.preventDefault();
var formData = new FormData($('#upload-file'));
$.ajax({
url: '/image',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
cache: false,
// contentType: false,
processData: false
});
});
Controller:
def image = Action(parse.temporaryFile) { request =>
request.body.moveTo(new File("/tmp/picture"))
Ok("File uploaded")
}
The problem was occuring in the Javascript, not the Scala. I was not referencing the form elements improperly.
var formData = new FormData($('#upload-file')[0]);
However, I also had problems with parse.temporaryFile and it was not properly storing the file using the code above. When I inspected the stored files in a text editor, I noticed it still had the ------WebKitFormBoundaryJ0uWMNv89fcUsC1t-- stuff at the beginning of the file, followed by the form information, then followed by the file bytes.
To fix this, I just used the default method for multipartform upload as per the Play Documentation, and it worked perfectly.
def image = Action(parse.multipartFormData) { request =>
request.body.file("picture").map { picture =>
val filename = picture.filename
picture.ref.moveTo(new File(s"/tmp/picture/$filename"))
Ok("ok")
}.getOrElse {
InternalServerError("file upload error")
}
}

Javascript pass input file to PHP

I don't want to upload a file using Javascript, I just want to pass by Ajax the file to a PHP file, and in the PHP make the validations I want, plus use the move_uploaded_file function. Is it possible?
$('#the_button').on("click", function(){
var image = $('#image').val() == "" ? null : $('#image').files;
$.ajax({
type: "POST",
url: "insert.php?type=image",
data: image,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
}
});
}
This returns 'undefined' for the #image.
$('#image').files[0] also returns undefined.
$('#image')[0].files returns [object FileList] -> is it correct?
try this plugin
http://blueimp.github.io/jQuery-File-Upload/
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
You can not upload files via AJAX.
Usual way is to set the target of your form to a hidden iframe.
Something like this.
<form target="myHiddenIframe" method="post" enctype="multipart/form-data">
//your form elements here.
</form>
<iframe name="myHiddenIframe" id="myHiddenIframe" style="display: none;" />
Submit the form to achieve what you want.

Categories