Use javascript to rename file before upload - javascript

Let's say I have this list of forms like so:
var forms = document.getElementsByClassName('uploadImage');
each item in this list look like this:
<form method=​"post" action=​"/​upload" enctype=​"multipart/​form-data" id=​"f_x" class=​"uploadImage">
​ <input type=​"file" id=​"u_x">​
<input type=​"submit" value=​"Submit" id=​"s_x">​
</form>​
where x = [0,1,2,3,4,5]
How do I loop through this list and do two things:
1 - Rename the file name
2 - Submit the form for uploading the file
I looked for many resources online like this one: https://www.telerik.com/forums/change-file's-name-when-it's-uploaded-via-html-form, all of them are using Jquery , I need it in javascript
update :-
I figured out how to get to the input value of each form
forms[0].elements[0] this will return the first input of the first form on the list
forms[0].elements[0].value this output the value of the file input

So here is the code you linked to, and I will break it down a bit after. A lot of it is vanilla javascript.
$(document).ready(function() {
initImageUpload();
function initImageUpload() {
$("#btn-submit").click(function(e) {
e.preventDefault();
var everlive = new Everlive({
appId: "",
scheme: "https"
});
// construct the form data and apply new file name
var file = $('#image-file').get(0).files[0];
var newFileName = file.filename + "new";
var formData = new FormData();
formData.append('file', file, newFileName);
$.ajax({
url: everlive.files.getUploadUrl(), // get the upload URL for the server
success: function(fileData) {
alert('Created file with Id: ' + fileData.Result[0].Id); // access the result of the file upload for the created file
alert('The created file Uri is available at URL: ' + fileData.Result[0].Uri);
},
error: function(e) {
alert('error ' + e.message);
},
// Form data
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false
});
return false;
});
}
});
As is mentioned, this uses jQuery $.ajax() to create an AJAX POST to the server with new FormData where the name of the file has been modified. The new FormData is then sent to the server instead of the HTML Form data.
So, when the button is clicked to submit the form, this event is prevented.
var file = $('#image-file').get(0).files[0];
This is then used to select the <input> element in jQuery and then collect the files info from the element.
var file = document.getElementById("image-file").files[0];
This can be done with JavaScript. Largely the rest of the script would be unchanged, except for the initialization and sending of POST Data via AJAX.
It might be best to create a function that you send the form to and it can then return the new form data with new name. As you did not want to provide an MCVE, it's hard to give you an example since it's not clear how the data for the new name would be create or gathered from.
function nameFile(inEl, newName){
var file = inEl.files[0];
var results = new FormData();
results.append('file', file, newName);
return results;
}
function sendFile(url, formData){
var request = new XMLHttpRequest();
request.open("POST", url);
request.send(formData);
}
sendFile("/​upload", nameFile(document.getElementById("file-image"), "UserFile-" + new Date().now() + ".jpg"));
Another issue is if you have multiple forms, and multiple submit buttons, which one will trigger all the items to get uploaded? Either way, you'd have to iterate each form (maybe with a for() loop) collect the form data from each, update the name, and submit each one, most likely via AJAX.
Hope this helps.

Related

Create FormData excluding not provided input file

I submit a form manually via jQuery. I use FormData with all input elements from this form.
See code below:
$("#submit-form").on('submit', function (event) {
event.preventDefault();
var form = $('#submit-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
url: "my-best-handler",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 60000
});
});
One of input elements is file and it's optional to set it. When it's not set, I don't need to use it in FormData and be sent with other elements to request handler.
The problem is that currently it will be sent even if it's not set.
I'm curious how I can exclude it from FormData if it's not set.
In worst case I can create FormData manually like here.
But I hope there is "black list" like approach by removing just not set file from FormData OR any other elegant way.
Update:
I came with the following solution:
if (!$("#input-file").val()) {
data.delete('input-file');
}
You can use the delete() function to remove your field
var form = $('#submit-form')[0];
var data = new FormData(form);
if (!$("#input-file").val()) {
data.delete('input-file');
}
Disabling input approach.
Disabled form controls never get submitted
$("#submit-form").on('submit', function (event) {
event.preventDefault();
// disable before creating FormData
$(this).find(':file').prop('disabled', function(){
return !this.files.length;
});
var form = $('#submit-form')[0];
var data = new FormData(form);
As mentioned in comments should re-enable in ajax success callback

How to upload FormData object using AngularJS

I am new to angular-js, and wants to submit the multipart/form-data with an image and it's $http.post() method supports only json format, so I want to convert formdata object to the json format,
$scope.SubmitForm=function()
{
url = siteurl + '/admin/' + $scope.module + '/add';
var form=document.getElementById("addForm");
var formData=new FormData(form);
$http({
url : url,
method : "POST",
data : formData,
})
.then(function(responseText) {
alert(JSON.stringify(responseText));
//process data
},function(){
alert("hello from error");
});
}
it didnot work for me; and i tried to make json format data for this and works fine
formData={
"first_name" : $('#first_name').val(),
"last_name" : $('#last_name'),
//....
};
but don't have any idea to append my image file to this format; what should i do right here to get my job.
Is there any way(function) to convert formdata object to json format
solved by putting two line of code like below, in $http configuration lines (thanks every body)-
$http({
url : url,
method : "POST",
data : formData,
transformRequest: angular.identity, // see the angugular js documentation
headers : {'Content-Type':undefined}// setting content type to undefined that change the default content type of the angular js
}).then(function(responseText){
alert(JSON.stringify(responseText));
///$scope.tablerows=$scope.totaltablerows;
///$scope.searchFunction();
},function(){
alert("hello from error");
});
just this works for me
You should really use ng-model when working with forms in angular (can you provide your form in your example?). It creates a scope variable to work with in your controller and you will have two way binding if it is already defined... for example as your form isn't present I'd do something like this, this is simplified (and not tested)...:
<form name="myForm" ng-submit="SubmitForm()">
Name: <input ng-model="fields.name">
Address: <input ng-model="fields.address">
....
</form>
and in your JS controller...
$scope.submitForm = function(){
var data = $scope.fields,
url = '/admin/' + $scope.module + '/add'; // I assume $scope.module is available from elsewhere...
$http.post(url, data).then(function(resp){
// do stuff...
});
}
There's more info here... https://docs.angularjs.org/api/ng/directive/ngModel and W3schools have some examples: http://www.w3schools.com/angular/angular_forms.asp
It Should be constructed like this:
var form = document.getElementById('addForm');
var fd = new FormData(form);
var file = this.files[0];
fd.append("afile", file);
// These way you add extra parameters
fd.append("first_name", $('#first_name').val());
fd.append("last_name", $('#last_name').val());
Reference example - from github

Checkboxes in Form to javascript to php

I have a form with dynamic checkboxes based on MySQL data. On submit the DIV refreshes without blinking with JavaScript. I'm trying to send the form data to PHP for updating the MySQL but I constantly run into one error or another due to my lack of JavaScript knowledge. My current attempt (see below) gives the "TypeError: document.multipix_form.pix is undefined" error in FireBug.
function multipicupdate(php_file, purpose, where) {
var request = getXMLHTTP(); // call the function for the XMLHttpRequest instance
var a = document.getElementById("optone").value ;
var b = document.getElementById("table").value ;
var boxes = document.multipix_form.pix.length
txt = ""
for (i = 0; i < boxes; i++) {
if (document.multipix_form.pix[i].checked) {
txt = txt + document.multipix_form.pix[i].value + " "
}
}
var the_data = 'purpose='+purpose+'&var1='+a+'&var2='+b+'&var3='+txt;
request.open("POST", php_file, true); // set the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
The form name is multipix_form. The three form inputs are optone (select), table (select), and pix[] (checkbox). The pix[] is dynamic as I said before. It is the passing of the checkbox data from JavaScript to php that has me stumped.
My form submit is :
<input type="button" onClick="multipicupdate('php/ajaxprocess.php', 'multipix', 'message_profile'); return false;" value="Save changes to this photo">
The ajaxprocess.php will take the form data and update MySQL.
As you have tagged jQuery, here's a jQuery solution. You can simplify this code quite a lot. Firstly, you can use serialize() to create a querystring from the values of the inputs in that form. Then you can use $.ajax to send that information to the page you need. Try this:
<input type="button" value="Save changes to this photo" id="multipicupdate">
$('#multipicupdate').click(function() {
$.ajax({
url: '',
type: 'POST',
data: $('#myForm').serialize(), // change the selector as needed
success: function(data) {
$('#message_profile').html(data);
}
});
});
You need a semicolon after
var boxes = document.multipix_form.pix.length
and
txt = ""

How to send image to .net Webservice using Ajax in IE8?

The folowing post is related to: How to send image to PHP file using Ajax?
I managed to get this working as per the above post, but it fails to work on IE8.
Is there a way to get this to work on ie8+?
Here is my code:
$("form[name='uploader']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: dotnetpage,
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('.js-ugc-image').attr('src', msg);
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
IE 8 does not have formdata, you can use a hidden iframe and post it and read the results.
I've used a technique that was something like this
Clone the form, move original form into a hidden iframe (this needs to be done because you cant clone or set input type files value on IE) and then submit and read the result of the submit.
Something like this which is a code i used before and worked:
var $form = $('your form');//GET YOUR FORM
//Create Hidden iframe
var _hiddenIframe = $('<iframe id="_hiddenframe" style="display:none;"></iframe>');
//Create Copy Form and add the attributes of the original
var _copyForm = $('<form id="_copyForm" name="_copyForm" style="">');
_copyForm.attr({'method':$form.attr('method'),'action':$form.attr('action'), 'enctype':$form.attr('enctype')});
//Get original fields
$original = $form.children('*');
//Clone and append to form
$original.clone(true).appendTo($form);
//send the original fields to hidden form
$original.appendTo(_copyForm);
//Add the iframe to the body
_hiddenIframe.appendTo('body');
//Add the form to the hidden iframe
_copyForm.appendTo(_hiddenIframe.contents().find('body'));
var $r;
//submit the form
_copyForm.submit();
//after it reloaded(after post)
_hiddenIframe.on('load',function(){
//read result (maybe a json??)
$r = $.parseJSON(_hiddenIframe.contents().find('body').text());
//Do something with the result
if($r.result=='ok'){
//Do Something if ok
}
else{
//Do Something if error
}
});
No,sorry, IE8 doesn't support the FormData object. (See http://caniuse.com/#search=formdata)
Whay you can do is embed the <input type='file > tag in a separate form and submit it using jQuery.

Access file upload field from ajax

I have a problem with accessing file upload field
//HTML
<input type='file' name='images' id="images" multiple>
//////////////////
$('.bt-add-com').click(function(){
var formdata = new FormData();
var sessionID = 8;
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var theFile = formdata.append("images", sessionID);
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&file='+formdata.append("images[]", sessionID),
success: function(html){
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
////RESULT
array (size=6)
'file' => string 'undefined' (length=9)
problem is when i access file upload field using formdata as code below. it display value as undefined. can't get uploaded file details
You're taking the form data object and appending it to a string. That won't work.
Don't try to build a string to pass to data, use the FormData API for all your fields, then pass the FormData object itself.
You also need to append the file data form the input instead of the number 8.
formdata.append("images", sessionID);
formdata.append("images[]", sessionID)
Don't use images and images[]. If you're using PHP, then use just images[]
Don't use sessionID, use the file.
formdata.append("images[]", document.getElementById('images').files[0]);

Categories

Resources