How to upload FormData object using AngularJS - javascript

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

Related

AJAX POST of tinyMCE contents - Character encoding of table entities

I'm using the tinyMCE editor plugin in my webpage.
When I use a simple HTML page post to post the contents to the backend PHP and save them to a database or file, all seems OK.
When I try to do the same using an AJAX post, I am finding it impossible to prevent encoding issues.
In particular (I'll escape it here) \&\n\b\s\p\; is being converted to  and a "-" character is being converted to �
I've tried a few suggestions but with little luck.
The suggestion is that it is either an issue with my charset or encoding.
My save function is as follows:
function letterSave(newfile,fname){
var newDate = new Date;
var uniq=newDate.getTime();
var input = $('#myTextareastdletter');
var contents=input.val();
var context='<?=(!strcmp($sessobj->mode,"SA_ViewAbs")?"A":"S");?>';
// alert(fname);
$.ajax({
type: "POST",
url: '<?=auto_version("./SVajaxSaveDocContents.php")?>?duff='+uniq,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {'S_sessid' : '<?=$sessobj->sessionid?>', 'context' : context, 'contents' : encodeURIComponent(contents), 'fname' : fname, 'newfile' : newfile},
success: function(data){
data = JSON.parse(data);
fname=data[0];
newLetterList=data[1];
if (fname != 'FAIL') {
alert ('OK: Letter Contents Saved to File ('+fname+').');
var versionOutput = $('#popupOutput');
versionOutput.html('');
var box = $('#popupDisplay');
var cover=$('#coverDiv');
box.css({
display:"none"
});
cover.css({
display:"none"
});
var letterOutput = $('#AbsenceLetters');
letterOutput.html(newLetterList);
} else {
alert ('Sorry: Failed to Save Letter Contents!');
}
},
error: function(data){
alert ('Sorry: Failed to Save Letter Contents!');
// console.log(data);
// console.log('error');
}
});
}
As you can see, I've been playing with setting the contentType and using encodeURIComponent().
Any help would be appreciated.
Cheers
In order to avoid these encoding issues, don't use .val on the textarea that the tinyMCE instance is attached to. Instead, you can utilize tinyMCE's built-in getContent method like so:
tinyMCEInstance.getContent()

Use javascript to rename file before upload

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.

AngularJS - How to send an audio file through $http post?

So I've been trying to send an audio file through an $http service using FormData, and so far what I have tried to send the file hasn't worked yet.
This is how the service looks like:
songs_services.add_new_song = function(new_song_name, new_song_artist, song) {
var fd = new FormData();
fd.append("new_song_name", new_song_name);
fd.append("new_song_artist", new_song_artist);
fd.append("song", song);
console.log(fd.get("new_song_name"));
console.log(fd.get("new_song_artist"));
console.log(fd.get("song"));
return $http.post(BACKEND_PREFIX + "add_new_song", fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function() {
}, function() {
});
};
I wanted to make sure that the information was actually been appended to my FormData and this is what i get in the console:
So now I know that the FormData has actually the information that I need.
I have also tried changing the Content-Type to multipart/form-data with no success also.
I'm also using CakePHP 2 as my backend, so this is how I'm trying to get the information:
public function add_new_song() {
$this->autoRender = false;
$data = json_decode(file_get_contents("php://input"));
print_r($data);
print_r($_POST);
print_r($_FILES);
$new_song_name = $_POST["new_song_name"];
$new_song_artist = $_POST["new_song_artist"];
$song = $_FILES;
echo $new_song_name;
echo "<br />";
echo $new_song_artist;
echo "<br />";
print_r($song);
die();
}
But echoing the variables only shows empty arrays and I also get an undefined index error when trying to access the variables from $_POST.
Is there any special way I should be sending the audio file through $http? I really feel like I'm missing a little detail.
At last, instead of using angularjs $http.post I decided to try with $.ajax and see what happened, and it actually worked!
Here's what I used:
$.ajax({
type : "post",
url : "uploads/songs",
data : fd,
cache : false,
contentType : false,
processData : false,
success: function() {
console.log("Hey");
}
});
And in Angular 6, you can do the following to send audio as FormData.
Inject the HttpClient:
constructor(private http:HttpClient){}
Use the POST method to send audio:
let url = 'http://destinationurl.com/endpoint';
let formData = new FormData();
formData.append('myAudioFile',audioFile);
this.http.post(url,formData).subscribe(response => {
//handle response
}, err => {
//handle error
});
the post method will automatically change the content type to multipart, so you need not set anything manually.

Submit dynamically created input from Angular to PHP Page

I am trying to create an invoice form, which can make all the necessary calculations like subtotal, tax total by itself .
Hitting the submit button should submit all values and the dynamically created items to a PHP page, which will insert these values (written by the user, or calculated by angularjs) to the appropriate SQL table/column as I wish.
Based on this project , I added this javascript code.
function PhpCtrl($scope, $http, $templateCache) {
var method = 'POST';
var url = 'added.php';
$scope.codeStatus = "";
$scope.add = function() {
var FormData = {};
$http({
method: method,
url: url,
data: FormData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).
success(function(response) {
$scope.codeStatus = response.data;
}).
error(function(response) {
$scope.codeStatus = response || "Request failed";
});
return false;
};
}
Can anyone help me how to store all the dynamically created items, along with their values, in order to submit them to a php page ?
You can create a FormData to be submitted dynamically using plain javascript like this:
var fd = new FormData();
fd.append("fieldName", valueToSubmit);
fd.append("arrayField[]",[1,2,3]); //you can even post array data
The you push fd to the server:
var uri = "added.php";
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,true);
xhr.onreadystatechange=function(){
if(xhr.readyState == 4 && xhr.status==200){
//do something with returned data
}
};
fd.append("img_file",blob_to_upload);// you can even upload a file
fd.append("user_id",data);
fd.append("category_id",category_id);
xhr.send(fd);

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