i want to hit api on form data like when I am using let params ={"supplier_id": "538","verify":"1","item_id":itemId};and api is this.aService.process('http://myapi.php', params) then it is not working .When I am trying with
let _urlParams = new URLSearchParams();
_urlParams.append('supplier_id', "538");
_urlParams.append('verify', "1");
_urlParams.append('item_id', itemId);
still it is not working and data is not showing in network . When I am using postman then if i am putting data on form-data then it is working and on raw it is not working .. What to do ?
URLSearchParams != FormData
Try sending your data with
let input = {
firstName: 'first name',
(...)
};
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('https://angular2.apispark.net/v1/contacts/', $.param(input), { headers })
.subscribe(...);
Related
I try to send an image from a ionic Front-End application through a post method to Back-End services in Spring boot
I have done this method that makes the post to the backend url with the image inside a FormData object:
uploadImageService(url: string, image: any) {
console.log('post service: upload Image', + url);
// Initiates a FormData object to be sent to the server
const fd: FormData = new FormData();
fd.append('file', image);
const xhr = new XMLHttpRequest;
console.log('form data file: \n' + fd.get('file'));
xhr.open('POST', url);
// Send the FormData
xhr.send(fd);
console.log(xhr.response);
return xhr.responseText;
}
// call this method:
this.webapiService.uploadImageService(this.globalDataService.getUrlMedium() 'riskcontrol/subir-imagen', this.selectedImage);
This is the spring boot method that collects this post:
#RequestMapping(method = RequestMethod.POST, value = "/subir-imagen")
public ResponseEntity handleFileUpload(#RequestParam("file") MultipartFile file) {
LOGGER.log(Level.INFO, "/Post, handleFileUpload", file);
String associatedFileURL = fileManagerService.storageFile(file);
return ResponseEntity.ok(associatedFileURL);
}
When I do the post of the image I get this error:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
I have launched the petition through Postman and it has worked,
that's why I think the error is in the tyscript code.
The only difference I see between postman and the code, is that in the form-data, let mark the key as type file or type text, and I have chosen type file.
I tried to make the request post in another way:
const httpOptionsImages = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE'
})
};
// function
uploadImageService(url: string, image: any): Observable<any> {
console.log('post service: upload Image', + url);
// Initiates a FormData object to be sent to the server
const fd: FormData = new FormData();
fd.append('file', image);
return this.http
.post(url, fd, httpOptionsImages);
}
// call to the function
this.webapiService.uploadImageService(this.globalDataService.getUrlMedium() + 'riskcontrol/subir-imagen', this.selectedImage)
.subscribe( result => {
console.log(result);
});
But in this way I got another error:
FileUploadException: the request was rejected because no multipart boundary was found
What am I doing wrong?
Is there any way to indicate to FormData that the key is of type file as in postman?
Add the image as a Blob follow Ionic tutorial
const imgBlob = new Blob([reader.result], {type: file.type});
formData.append('file', imgBlob, file.name);
In the readFile function the program utilizes the FileReader from the File API to read the file into an ArrayBuffer. The onloadend event is called as soon as the file is successfully read. The app then creates a FormData object, wraps the array buffer in a Blob and adds it to the FormData object with the name 'file'. This is the same name the server expects as request parameter.
Remove your 'Content-Type': 'multipart/form-data'.
Have you tried on using #RequestPart instead of #RequestParam for MultipartFile file.
I'm working with Laravel API and calling an API method in two different way. In one-way form validation working but in second-way form validation not working. But I really need second-way of API call.
saveMember: function () {
let that = this;
let formData = new FormData();
formData.append('member_info', that.member_info);
// member_info is a Json Object
// This is First way , form validation working good while calling Api
axios.post('/api/member/save_member', that.member_info)
// This is second way, form validation not working
axios.post('/api/member/save_member', that.formData)
.then(function (response) {
console.log("response Here: " + response.data.success);
that.errors = response.data.success;
// location.reload(true);
})
.catch(function (error) {
that.errors = error.response.data.errors;
console.log("Error Here: " + error.response.data);
});
}
Doing form validation in Laravel Request Controller.
Look like Json Object can send to API.
I missing your error when request call to fixed.
But i think you need convert FormData to Json Object:
var obj = {};
that.formData.forEach(function(val, idx){
obj[idx] = val;
});
var json = JSON.stringify(obj);
and then resend:
axios.post('/api/member/save_member', json)
...
I am trying to upload a file to the REST Api of Octoprint, which should be done by sending a POST request with Content-Type: multipart/form-data
(http://docs.octoprint.org/en/master/api/fileops.html#upload-file)
I am using NodeJS and two libraries, XmlHttpRequest and form-data. When trying:
var xhr = new xmlhttprequest() ;
var form = new formData() ;
form.append('exampleKey', 'exampleValue');
xhr.open("POST","octopi.local/api/local", true) ;
xhr.setRequestHeader("Content-Type","multipart/form-data") ;
xhr.send(form) ;
I get an error at the xhr.send line :
TypeError: first argument must be a string or Buffer
If I make a synchronous request by using xhr.open("POST",url,false), this error disappears.
Why is it so ? Is there a way to turn it into an asynchronous request ?
EDIT Actually, I don't really understand the documentation. I suppose that I should set the file I want to upload by using form.append("filename", filepath, "exampleName"), but I am not sure about that. The fact is that I noticed that I get the TypeError even if I try a simplified request, without sending any file.
EDIT2 This is the modified code, which returns the same error :
var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest ;
var FormData = require('form-data');
var data = new FormData();
data.append("key","value" );
var xhr = new XMLHttpRequest();
xhr.open('POST', "octopi.local/api/files/");
xhr.send(data);
After a long time working on this, I finally managed to upload a file. If you use NodeJS, don't rely on the MDN documentation: it tells what the libraries should do, not what they can actually do on the node platform. You should only focus on the docs available on GitHub.
It seems that it is not currently possible to send a form with XMLHttpRequest : I tried using JSON.stringify(form) but then wireshark tells me that the request is not a multipart/formdata request.
If you want to upload a file, you should rather use the 'request' module. The following has worked for me :
exports.unwrappeduploadToOctoprint = function(){
"use strict" ;
var form ={
file: {
value: fs.readFileSync(__dirname+'/test2.gcode'),
options: { filename: 'test2.gcode'}
}
};
var options = {
method: 'POST',
url: 'http://192.168.1.24/api/files/local',
headers: { 'x-api-key': 'E0A2518FB11B40F595FC0068192A1AB3'},
formData: form
};
var req = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
};
Seems that you have some typos in your code. Use code snippet below instead. Replace the relevant parts according to your needs
var fileToUpload = document.getElementById('input').files[0];
var data = new FormData();
data.append("myfile", fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_endpoint");
xhr.send(data);
I'm trying to send a post request to another service (a Spring application), an authentication, but I'm having trouble constructing a functional Angular2 post request at all. I'm using this video for reference, which is pretty new, so I assume the information still valid. I'm also able to execute a get request with no problems.
Here's my post request:
export class LogIn {
authUser: string;
authPass: string;
token: any;
constructor(private _http:Http){}
onSubmit() {
var header = new Headers()
var json = JSON.stringify({ user: this.authUser, password: this.authPass })
var params2 = 'user=' + this.authUser + '&password=' + this.authPass
var params = "json=" + json
header.append('Content-Type', 'application/x-www-form-urlencoded')
this._http.post("http://validate.jsontest.com", params, {
headers: header
}).map(res => res.json())
.subscribe(
data => this.token = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
console.log(this.token);
}
}
The info is being correctly taken from a form, I tested it a couple of times to make sure. I am also using two different ways to build the json (params and params2). When I try to send the request to http://validate.jsontest.com, the console prints undefined where this.token should be. When I try to send the request to the Spring application, I get an error on that side:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Does anyone know what I'm doing wrong?
In fact you need to use the GET method to do that:
var json = JSON.stringify({
user: this.authUser, password: this.authPass
});
var params = new URLSearchParams();
params.set('json', json);
this._http.get("http://validate.jsontest.com", {
search: params
}).map(res => res.json());
See this plunkr: http://plnkr.co/edit/fAHPp49vFZJ8OuPC1043?p=preview.
before starting let me say that I am new to dojo and this is my first project in dojo:
when I am trying to send json data from rest client (some chrome ext) it working for me,I mean to say that my spring mvc part is working, but when i am trying to send the same json from dojo code I am getting http 400 exception
my dojo code:
postCreate : function() {
this.inherited(arguments);
var form = dom.byId("contactSubmit");
on(form, "click", function(evt) {
var box0 = registry.byId("inputEmail");
var box1 = registry.byId("inputName");
var box3 = registry.byId("message");
alert("values are: " + box0.get("value"));
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
request.post("/pool/conta", {
data: jsonData,
handleAs: "json",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
}
}).then(function(text){
alert("values are send"+text);
});
});
}
the jason data that I am sending from rest client is which is working:
{"email":"some#gmail.com","inputName":"some name","message":"some msg"}
my spring mvc method is below:
#RequestMapping(value="/conta", method = RequestMethod.POST)
public #ResponseBody Contact getShopInJSON(#RequestBody Contact contact2) {
Contact contact = new Contact();
contact.setEmail("pro#gmail.com");
contact.setInputName("pro");
contact.setMessage("msg");
System.out.println("***********************"+contact2.getEmail());
return contact;
}
pool is name of application
The json data as passed in post request requires string to be crypted with "\" so that the javascript can handle the double codes as is within string(double quoted string).
Thus, the line
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
would work if written as below
jsonData = " {\"email\":\"some#gmail.com\",\"inputName\":\"some name\",\"message\":\"some msg\"} " ;
Its working now, I have used toJson from dojo/_base/json" utility before passing it to request.post