Using FormData for casper file upload - javascript

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?

Related

Create a file object of zip file based on a blob for formdata in a fetch

I would like to upload a zip file as part of formdata in a Javascript fetch.
I can easily send in a zip file which I have read in via a file input control (see first segment of code). But when try to create a file object based on a blob, I receive an error (see second segment of code).
Basically I am asking how to create a zip file object from a blob. I tried many variations of code, but cannot nail the right syntax of creating the file object from blob, but it has to be a zip file. Note that the zip file is a shapefile - not sure if it makes any difference.
//here we upload the zip file
var fileInput = document.getElementById('avatar');
var filename = fileInput.files[0].name;
//This works fine. I can easily send the zip file in formdata
var headers = new Headers();
headers.set('X-CSRFToken', csrftoken);
var formData = new FormData()
formData.set("time", false)
formData.set("base_file", fileInput.files[0] )
fetch("/upload/", {
"credentials": "include",
"body": formData,
"headers": headers,
"method": "POST",
"mode": "cors"
})
But when I try to upload zip file I created from a blob, then I receive an error
var shpBuffer = await ShapeFileFromGeoJSON(geojson, fileName);
var base64String = Uint8Array.from(window.atob(shpBuffer), (v) => v.charCodeAt(0));
var shapeFileBlob = new Blob([ base64String ], {type:"application/zip"});
saveAs(shapeFileBlob, fileName); //this works and a zip file is saved
var file = new File([shapeFileBlob], 'application.zip', { type: shapeFileBlob.type,});
console.log(file);
//Returns: "File {name: 'application.zip', lastModified: 1656002582746,
//lastModifiedDate: Fri Jun 24 2022 04:43:02 GMT+1200 (New Zealand Standard Time),
//webkitRelativePath: '', size: 6091726, …}"
console.log(file instanceof File); //returns true
var headers = new Headers();
headers.set('X-CSRFToken', csrftoken);
var formData = new FormData()
formData.set("time", false)
formData.set("file", file)
fetch("/upload/", {
"credentials": "include",
"body": formData,
"headers": headers,
"method": "POST",
"mode": "cors"
})
The error returned in the console is
POST https://WEBSITE/upload/ 400 (Bad Request)
{success: false, errors: Array(1)}
Yes, I think I solved the question. The issue was in the way I was creating the zip file - which is a shapefile. The shapefile zip file should unzip into the files directly without into any intermediate folder. Geoserver was rejecting it as upon unzipping it could not directly find any shapefile.

Sending a blob over ajax post

I am trying to send an audio blob over to my Rails action through an ajax POST. I seem to get over to the Rails action but the data I am sending appears to be empty and my audio file is not saved. I can do this with simple javascript, but I cannot seem to get this to work with ajax.
Ajax not working:
function sendRecToPostAjax(blob){
var data = new FormData();
data.append("audio", blob, (callid + ".oga"));
data.append('callid', callid);
return $.ajax({
url: '/controller/action',
type: 'POST',
cache: false,
data: data,
processData: false,
contentType: false
});
}
JS working:
function sendRecToPost(blob) {
var data = new FormData();
data.append("audio", blob, (callid + ".oga"));
data.append('callid', callid);
var oReq = new XMLHttpRequest();
oReq.open("POST", "/controller/action");
oReq.send(data);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("Uploaded");
} else {
console.log("Error " + oReq.status + " occurred uploading your file.");
}
};
}

Sending files from client (angular) to server Asp.net wed api, request always has empty prorerty "files"

everyone, have a trouble with sending files
I have angularjs client:
var fd = new FormData();
var myEl = angular.element( document.querySelector( '#someId' ) );
fd.append('file', myEl[0].files[0]);
fd.append('test', 'value');
var vv = $resource('api/:domen/:url', { url: "", domen: 'Options' }, {
'saveF': {
headers: {
'Authorization': 'Bearer ' + currentUser.getProfile().token,
'Content-Type': false
},
method: 'POST'
}
});
vv.saveF({ url: "UploadData", domen: 'Info' }, fd, function (el) {
console.log(el);
});
The client code send fields, I can check it via Fiddler, the file is in body
and backend code on ASP.NET Web Api:
public async Task<IHttpActionResult> UploadData()
{
// var a = HttpContext.Current.Request;
// var f = a.Files.Get(0);
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
and so on
The request always fails, because of "Request.Content.IsMimeMultipartContent()" or var f = a.Files.Get(0);
and I cannot get the file, server never see a content in request, but can see content-length
Already try to white content type 'multipart/form-data' but id didn`t help
Please, if somebody knows how to fix it - answer
See back-end implementation of Web API 2: https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2
Also, you can use ng-file-upload for AngularJS
And example: https://github.com/stewartm83/angular-fileupload-sample
If you upload unknown MIME type and host your application on IIS,
it would be good add MIME type to IIS.

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

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);

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']
}

Categories

Resources