JS: Extend request body data while uploading a file - javascript

Consider this snippet:
fetch(encodeURI(insertObjectUrl), {
method: 'POST',
body: input.files[0]
})
Written in this way, the request body includes:
File content
File size
File content type
etc.
However, I would like to add also additional information, for instance manually providing a contentDisposition value (see Object: insert).
How can I modify the code above to extend the request body?
I.e.
body: {
'file': input.files[0];
'contentDisposition: 'myvalue'
}

From the docs https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch:
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
Based on this you can only pass data via the body. That being said you can add the contentDisposition (key,value) into the body as follows:
jsonData = {
'file': input.files[0];
'contentDisposition: 'myvalue'
}
Then in your request:
fetch(encodeURI(insertObjectUrl), {
method: 'POST',
body: JSON.stringify(jsonData)
})
On the server you will need to convert the 'stringified' JSON data into object (using JSON.loads or another function).
Hope this helps

Related

How to have config parameter in axios post request with headers required

I was trying to send a post request using axios in my react code which needed both
'headers parameter' and 'config parameter' at the same time. I found out that there is two types for writing post requests in axios:
axios.post(url, data, config)
axios({
url :url,
method: 'post',
headers: headers,
data: data
})
In type 1 we can't send headers parameter and in type 2 we can't send config parameter.
So is there any way to solve this problem?
I solved it using xml httpRequest instead of axios, but I'm curious about the way we could solve it using axios.
base on doc
you can set header in config !
axios.post(url, data, {headers : {'X-Requested-With': 'XMLHttpRequest'} })
or you can send all options as a object
axios.request ({
url: '/user',
method: 'post',
data: {
firstName: 'Fred'
},
headers: {'X-Requested-With': 'XMLHttpRequest'},
// ... and other options
})
your assumption is wrong you can set the headers in the request config
https://github.com/axios/axios#request-config
{
headers: {'X-Requested-With': 'XMLHttpRequest'},
...
}

put request in angular sends empty form data

I am trying to make a put request.
The api requires an array of numbers as request parameter
$http({
'requestpath/putrequesturl',
{
categories: [categorylist]
},
{
'method': 'PUT',
'authToken': authToken,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
the data is sent as
requestpath/putrequesturl?categories=%5B5,19,12%5D
the query string parameter shows correct data, but Form Data in chrome dev tools is empty.
I tried this without content-type too, but it does not work
How can i make this request to send data as Form Data (Request body)
Edit: this is what api requires to get sent (if this is necessary):
Parameter: categories type:array
Your $http params looks a little odd. Maybe you are trying to do something like this..
$http({
method: "PUT",
uri: 'requestpath/putrequesturl',
headers: {
"Content-Type": "application/json",
"authToken": authToken // assuming this should be in the header
},
data: {
categories: [categorylist]
}
})
This is how the method put should seems
$http({
method: 'PUT',
url: uri,
headers: {"Content-Type": "application/json;charset=UTF-8"},
data: someData
});
or
$http.put(url, data, config)

Unpack data in PHP

I am using angular js and php. I have an array to post in my controller from js file. I have converted my array to JSON and tried to pass the data like below
var update = {
method: 'POST',
url: apiPoint.url + 'up.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params :{
alldatas: JSON.stringify($scope.alldata) ,
section : 'A',
}
By doing this I am getting 414 status error code. The url is too long.
So I have tried JSONC to pack my data..
I use jsonc.min.js and have updated my code as below.
var update = {
method: 'POST',
url: apiPoint.url + 'up.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params :{
alldatas: JSONC.pack($scope.alldata) ,
section :'A',
}
Now my data is passing through url and in my controller I get the data. But I can't unpack the data. Please help me to unpack the data.
I suppose you are using the standard $http component, and the mentioned JavaScript object stands for its configuration object.
You should pass JSON data through POST, i.e. the request body, because the request URI length is limited. The params option is serialized into GET.
So you need to move your data (alldatas) into data option:
var req = {
method: 'POST',
url: apiPoint.url + 'up.php',
data: { alldatas: $scope.alldata },
// you might even stringify it
//data: JSON.stringify({ alldatas: $scope.alldata }),
headers: { 'Content-Type': 'application/json;charset=utf-8' },
params: { section : 'A' }
};
$http(req).then(function (response) {
console.log(response.data);
});
For the application/x-www-form-urlencoded content type you should build a query string:
var req = {
method: 'POST',
url: apiPoint.url + 'up.php',
data: 'alldatas=' + encodeURIComponent(JSON.stringify($scope.alldata)),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
params: { section : 'A' }
};
The $_POST superglobal is filled only for application/x-www-form-urlencoded and multipart/form-data content types. The other content types are available via the php://input stream:
if (!empty($_POST)) {
$obj = $_POST;
} else {
$json = file_get_contents('php://input');
$obj = json_decode($json);
}
if ($obj) {
header('Content-Type: application/json');
echo json_encode($obj);
}
exit();

Download fails for large json string -Angular JS

I've written an application in angular for file download, the application is working fine only for small json string, but comes to large string the download fails. Can anyone please tell me some solution for this.
I'm using REST webservice
var json = _.getJson(); // here json value object be received from a script function
var myURL = 'rest/myMethod?jsonValue=' + JSON.stringify(json);
_.downloadFile(myURL);
The downloadFile method :
downloadFile: function(URL)
{
$.fileDownload(URL).done(function(e, response)
{
console.log('download success');
}).fail(function(e, response)
{
console.log('fail');
});
}
As per the comments, here's how to POST using Angular. I can only give you an example here. Header might depend on the angular version etc etc.
function TestController($scope, $http) {
$http({
url: 'yourwebsite',
method: "POST",
data: json, //this is your json data string
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
//upload succesfull. maybe update scope with a message?
}).error(function (data, status, headers, config) {
//upload failed
});
}
I see two potential problems:
The request URL might be too long (see: this discussion)
The stringified JSON contains characters not valid in a URL
If the URL is too long, you'd have to move the jsonValue into the body of your request rather than passing it as a URL parameter.
To address the second problem, you need to URI encode the stringified value:
var myURL = 'rest/myMethod?jsonValue=' + encodeURIComponent( JSON.stringify(json) );
BTW, looking at tha fail parameters should indicate why the request failed in the first place.
Here is an example for using $http of Angular for sending a post request and download a XML file from the server.
$http({
url: '$your_URL_here$', // you should replace $your_URL_here$ by your own url
method: 'POST',
responseType: 'arraybuffer',
data: postJson, //***this is the request json data for post***
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).success(function(data){
var blob = new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
saveAs(blob, $fileName$);// you should replace $fileName$ by your own fileName
}
}).error(function(data){
//Some error handling method here
});
Please note that you should import the FileSaver.js to save the file from 'arraybuffer' responseType.

Dojo /JSON post request on method with multiple parameters?

This should be basics but I'm having trouble with posting multiple parameters from dojo on a rest endpoint. I have the following method on my back end exposed via resteasy.
#POST()
#Path("/updateProduct")
#Consumes(MediaType.APPLICATION_JSON)
public void updateGeneralSettings(String session,Product product) {
System.out.println("session"+session);
System.out.println("product"+product.toString);
}
This works perfectly fine just with Product as the parameter. I'm yet to figure out how to build a jason string with another parameter. Product data just binding from form and this is some additional parameter I wanted to attach with it (i.e. session).
jsonData = dojo.toJson(product)
var handler = request.post(url, {
data: jsonData,
headers: {
"Content-Type": 'application/json; charset=utf-8',
"Accept": "application/json"
}
});
Appreciate if you guys can give me some solution.
Try adding parameter names to your method signature:
public void updateGeneralSettings(#FormParam("session") String session, #FormParam("product") Product product)
and then something like:
var handler = request.post(url, {
data: {
session: session,
product: jsonData
},
headers: {
"Content-Type": 'application/json; charset=utf-8',
"Accept": "application/json"
}
});

Categories

Resources