Can't stop jasmine-ajax from trying to parse FormData object - javascript

I'm making a POST with AJAX and trying to test the data that gets sent, but I'm getting the error "paramString.split is not a function" when that test runs. I've looked for other posts about this but they all seem to be about getting FormData to work with AJAX, which I'm not having trouble with. The data sends, but I can't write a successful test around it.
AJAX:
upload: (file, progressCallback) => {
let data = new FormData();
data.append('image', file);
return $.ajax({
xhr: function() {
let xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', progressCallback);
return xhr;
},
method: 'POST',
url: apiUrl(),
cache: false,
processData: false,
contentType: false,
data: data
});
}
Test:
describe('my test', () => {
beforeEach(function() {
jasmine.Ajax.install()
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it('sends a POST request to the right endpoint with data', function() {
const image = {
size: 10000,
type: 'image/jpeg'
};
let data = new FormData();
data.append('image', image);
myService.upload(image); // POST happens here
const request = jasmine.Ajax.requests.mostRecent();
expect(request.method).toBe('POST'); // passes
expect(request.url).toBe('/dashapi/dam-assets/'); // passes
expect(request.data()).toEqual(data); // error
});
Error
TypeError: paramString.split is not a function
The error is occurring at this line:
https://github.com/jasmine/jasmine-ajax/blob/master/src/paramParser.js#L18. I put a breakpoint there and paramString is actually a FormData object at that point. I'm assuming that mocking out the request with jasmine.Ajax.install is overwriting the processData: false I have in the original request, but I'm not sure how to fix that.

I had to change the test to be
expect(request.params).toEqual(data);

Related

Sending json with files nested in lists with ajax

I am developping a form with some basic inputs and a mini form (in a popup) with a list of foos and each foo have its own attachement file
{
// form fields
...
foos: [
{
// foo form fields
...
attachment: { /* File type */ }
},
...
]
}
before i add the attachement property (file upload), everything work good when i submit the whole form with axios to the backend api server (i am using redux-form to manage the form state)
I use JSON.stringify(formValues) to send data with axios as json
But when i add the attachement property i don't know how to send the form because i read that with the file involved in the form i can't no longer send the form as json but I have to use FormData
The problem is I have nested file objects within a list so how can i send the whole form ?
I achieved the same as this.
let formData = new FormData();
formData.append("file", file);
//here my formData is in JSON format
formData.append("formData", JSON.stringify(formData));
const config = {
method: "POST", //change according to your API
data: formData,
url: api, //API Url
headers: {
"Content-Type": "multipart/form-data",
}
};
axios
.request(config)
.then(function(response) {
console.log(response.data);
}
})
.catch(error => {
console.log(error);
});
Declare a state variable Images which is an array type.
On change of file input assign files to Images array (handleOptionImages()).
Append this Images array in the formData object along with other form data.
Finally, send the formData object in your axios request.
<form>
<input type="file" onChange={e =>this.handleOptionImages(e)}>
<input type="file" onChange={e =>this.handleOptionImages(e)}>
<input type="text" name="user" value={this.state.value} onChange={e=>this.handleChange(e)}>
<button onClick={e=>submitForm(e)}>submit</button>
</form>
define a constructor with blank state like
constructor(props) {
super(props);
this.state = {
user:"",
Images:[]
}
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleOptionImages(e) {
let Images = this.state.Images.slice();
let media = e.target.files[0];
Images[] = media; // Update it with the modified email.
this.setState({ Images: Images });
}
submitForm(e){
let formdata = new FormData();
formdata.append("user",this.state.user);
if (this.state.Images) {
for (const file of this.state.Images) {
formdata.append("Images[]", file);
}
}
// add your axios code
axios.post("your api path", formdata)
.then(res => {
//handle success
} else {
// handle error
}
});
}
Please have a look I hope it will help you.
Thanks
To set a content-type you need to pass a file-like object. You can create one using a Blob.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
jQuery + Ajax for more details refer link
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});

Using FormData for casper file upload

This is my code:
var content = fs.read('test/test.png');
var formData = new FormData();
var blob = new Blob([content], {type:'image/png'});
formData.append('picture',blob);
require('utils').dump(formData);
this.open("http://localhost:8080/dns_capcha", {
headers:{
'Content-type':'image/png'
},
method: 'post',
data:formData
});
With this code I am getting this error:
CasperError: open(): invalid request settings data value: [object FormData]
Could somebody tell my what I have done wrong in this code?

How encode in base64 a file generated with jspdf and html2canvas?

i'm trying encode the document generated in the attached code, but nothing happens, not generate error but neither encodes the file, and the ajax request is never executed
what is the correct way?
html2canvas(document.getElementById("workAreaModel"), {
onrendered: function(canvas)
{
var img = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", "letter");
doc.addImage(img, 'JPEG',20,20);
var fileEncode = btoa(doc.output());
$.ajax({
url: '/model/send',
data: fileEncode,
dataType: 'text',
processData: false,
contentType: false,
type: 'GET',
success: function (response) {
alter('Exit to send request');
},
error: function (jqXHR) {
alter('Failure to send request');
}
});
}
});
First, jsPDF is not native in javascript, make sure you have included proper source, and after having a peek on other references, I think you don't need btoa() function to convert doc.output(), just specify like this :
doc.output('datauri');
Second, base-64 encoded string is possible to contain ' + ' , ' / ' , ' = ', they are not URL safe characters , you need to replace them or you cannot deal with ajax .
However, in my own experience, depending on file's size, it's easy to be hell long ! before reaching the characters' length limit of GET method, encoded string will crash your web developer tool first, and debugging would be difficult.
My suggestion, according to your jquery code
processData: false,
contentType: false
It is common setting to send maybe File or Blob object,
just have a look on jsPDF, it is availible to convert your data to blob :
doc.output('blob');
so revise your code completely :
var img = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", "letter");
doc.addImage(img, 'JPEG',20,20);
var file = doc.output('blob');
var fd = new FormData(); // To carry on your data
fd.append('mypdf',file);
$.ajax({
url: '/model/send', //here is also a problem, depends on your
data: fd, //backend language, it may looks like '/model/send.php'
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
alter('Exit to send request');
},
error: function (jqXHR) {
alter('Failure to send request');
}
});
and if you are using php on your backend , you could have a look on your data information:
echo $_FILES['mypdf'];
This code is for capturing Html page from screen and save as Pdf and send to back end api As blob
const filename = 'form.pdf';
const thisData = this;
this.printElement = document.getElementById('content');
html2canvas(this.printElement).then(canvas => {
this.pdfData = new jsPDF ('p', 'mm', 'a4');
this.imageHeight = canvas.height * 208 / canvas.width;
this.pdfData.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 208, this.imageHeight);
this.pdfData.save(filename);
this.uploadFile(this.pdfData.output('blob'));
});
}
uploadFile(pdfFile: Blob) {
this.uploadService.uploadFile(pdfFile)
.subscribe(
(data: any) => {
if (data.responseCode === 200 ) {
//succesfully uploaded to back end server
}},
(error) => {
//error occured
}
)
}

How can i get data from FormData in javascript?

I need to read data from FormData? I try to read something like someFormatData["valueName"] but it not working.
options["fileId"] or options["file"] does not work. Also I try options.fileId same result:
function upload(file, fileId, callback) {
var formData = new FormData();
formData.append("file", file);
formData.append("fileID", fileId);
$.ajax({
url: '/url',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
callback(response);
}
});
}
asyncTest("test upload chunk", function() {
var blob = new Blob(["Hello world!"], { type: "text/plain" }),
options = null,
fileID ="someFileID",
response;
jQuery.ajax = function(param) {
options = param; // THIS is FormData object
// how to read fileId and file from here
};
upload(blob, fileID, function (data) {
response = data;
});
options.success({
someProp: 'responseFromServer'
});
setTimeout(function() {
QUnit.equal(options, "dataTosend", "parameters is OK");
QUnit.equal(response["someProp"], "responseFromServer", "Response ok");
start();
},1000);
});
If you take your FormData object you can use a few different methods on it… What you are looking for is
formData.get()
or
formData.getAll()
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Note that the get() method is not fully supported on all browsers.
You can read using this
formData.get('fileId') // to read Id
formData.get('file') // to read the file
Another way to list all entries of a FormData :
for(const entry of formData){
console.log(entry); // Array: ['entryName', 'entryValue']
}

Backbone.js and FormData

Is there any way using Backbone.js and it's model architecture that I can send a formdata object to the server? The problem I'm running into is that everything Backbone sends is encoded as JSON so the formdata object is not properly sent (obviously).
I'm temporarily working around this by making a straight jQuery ajax request and including the formdata object as the data property, but this is less than ideal.
Here is a solution by overriding the sync method, which I use to allow file uploads.
In this case I override the model's sync method, but this can also be the Backbone.sync method.
var FileModel = Backbone.Model.extend({
urlRoot: CMS_ADMIN_URL + '/config/files',
sync: function(method, model, options){
// Post data as FormData object on create to allow file upload
if(method == 'create'){
var formData = new FormData();
// Loop over model attributes and append to formData
_.each(model.attributes, function(value, key){
formData.append(key, value);
});
// Set processData and contentType to false so data is sent as FormData
_.defaults(options || (options = {}), {
data: formData,
processData: false,
contentType: false
});
}
return Backbone.sync.call(this, method, model, options);
}
});
EDIT:
To track upload progress, you can add a xhr option to options:
...
_.defaults(options || (options = {}), {
data: formData,
processData: false,
contentType: false
xhr: function(){
// get the native XmlHttpRequest object
var xhr = $.ajaxSettings.xhr();
// set the onprogress event handler
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
console.log('%d%', (event.loaded / event.total) * 100);
// Trigger progress event on model for view updates
model.trigger('progress', (event.loaded / event.total) * 100);
}
};
// set the onload event handler
xhr.upload.onload = function(){
console.log('complete');
model.trigger('progress', 100);
};
// return the customized object
return xhr;
}
});
...
Just to add an answer to this question, heres how I went about it without having to override the sync:
In my view, I have somethign like:
$('#' + $(e.currentTarget).data('fileTarget')).trigger('click').unbind('change').bind('change', function(){
var form_data = new FormData();
form_data.append('file', $(this)[0].files[0]);
appManager.trigger('user:picture:change', form_data);
});
Which then triggers a function in a controller that does this:
var picture_entity = new appManager.Entities.ProfilePicture();
picture_entity.save(null, {
data: data,
contentType: false,
processData: false,
});
At that point, I'm overriding jQuery's data with my FormData object.
I had a similar requirement and here is what i did :
In View :
var HomeView = Backbone.View.extend({
el: "#template_loader",
initialize: function () {
console.log('Home View Initialized');
},
render: function () {
var inputData = {
cId: cId,
latitude: latitude,
longitude: longitude
};
var data = new FormData();
data.append('data', JSON.stringify(inputData));
that.model.save(data, {
data: data,
processData: false,
cache: false,
contentType: false,
success: function (model, result) {
alert("Success");
},
error: function () {
alert("Error");
}
});
}
});
Hope this helps.
I had the same issue. You can see above the way i solve it.
var $form = $("myFormSelector");
//==> GET MODEL FROM FORM
var model = new MyBackboneModel();
var myData = null;
var ajaxOptions = {};
// Check if it is a multipart request.
if ($form.hasFile()) {
myData = new FormData($form[0]);
ajaxOptions = {
type: "POST",
data: myData,
processData: false,
cache: false,
contentType: false
};
} else {
myData = $form.serializeObject();
}
// Save the model.
model.save(myData, $.extend({}, ajaxOptions, {
success: function(model, data, response) {
//==> INSERT SUCCESS
},
error: function(model, response) {
//==> INSERT ERROR
}
}));
The hasFile is a custom method that extends the JQuery functions.
$.fn.hasFile = function() {
if ($.type(this) === "undefined")
return false;
var hasFile = false;
$.each($(this).find(":file"), function(key, input) {
if ($(input).val().length > 0) {
hasFile = true;
}
});
return hasFile;
};
Just use Backbone.emulateJSON = true;: http://backbonejs.org/#Sync-emulateJSON
will cause the JSON to be serialized under a model parameter, and the request to be made with a application/x-www-form-urlencoded MIME type, as if from an HTML form.
None of the answers worked for me, below is simple and easy solution. By overriding sync method and options.contentType like this:
sync: function(method, model, options) {
options = _.extend({
contentType : 'application/x-www-form-urlencoded;charset=UTF-8'
}, options);
options.data = jQuery.param(model.toJSON());
return Backbone.sync.call(this, method, model, options);
}
A simple one will be, hope this will help someone.
Create a object of Backbone Model:
var importModel = new ImportModel();
Call Save[POST] method of Backbone Model and Pass the FormData Object.
var objFormData = new FormData();
objFormData.append('userfile', files[0]);
importModel.save(objFormData, {
contentType: false,
data: objFormData,
processData: false,
success: function(data, status, xhr) { },
error: function(xhr, statusStr) { }
});

Categories

Resources