I am trying to call Asp.Net WebApi method declared as:
[HttpPost]
[ActionName("Login2")]
public bool Login(UserInfo userinfo)
{
return userinfo.Username == "sandeep#sa.com" && userinfo.Password == "chandra";
}
And from Restangular the code looks like:
var lUserInfo = { Username: this.fEmail, Password: this.fPassword };
this.fLoginService.withConfig(x => x.setDefaultHeaders({ 'Content-Type': 'application/json' }))
.all("v1Values").post("Login2", null,
{ userinfo: lUserInfo }).then(
x => {
var lLoggedIn: boolean = x == "true";
this.fSessionService.fUserAuthenticated = lLoggedIn;
if (lLoggedIn) {
this.fLocation.path('/dashboard');
return;
}
Utilities.Dialog.showError('Invalid Email or Password');
});
I get this error:
"OPTIONS http://myserver:7220/api/v1Values 500 (Internal Server Error)"
I just can't get this to work. I can't see userinfo passed in the body.
What am I doing wrong?
Related
I'm having some problems passing the data from my razor page to the server. It is passing NULL value from my abp.ajax({. Is there anything I'm missing from my ajax or the server-side code:
I'm using RAZOR PAGES ABP Framework 5.3
MY AJAX:
$("#frmDistrict").on("submit",
function (event) {
event.preventDefault();
const Url = $(this).attr("action");
const formData = $(this).serialize();
abp.ajax({
type: 'POST',
url: url,
data: JSON.stringify(formData)
}).then(function (result) {
if (data.isValid) {
if (data.IsNew) {
abp.notify.success(data.retmsg);
window.location.href = data.returl;
} else {
}
abp.notify.success(data.retmsg);
} else {
DisplayModelStateErrors(data.retmsg);
}
}).catch(function () {
alert("request failed :(");
});
});
MY SERVER CODE:
public async Task<JsonResult> OnPostAsync()
{
var rt = await Mediator.Send(new CreateDistrictCommand
{
District = district
});
if (rt.Failed) return new JsonResult(new { isValid = false, IsNew = true, retmsg =
rt.Message, sdata = rt.Data });
var retmsg = "District " + rt.Data.Name + " Created successfully.";
var returl = "/Districts/";
return new JsonResult(new { isValid = true, IsNew = true, retmsg, returl });
}
MY FORM
<form method="post" id="frmDistrict" >
<partial name="_AddEditDistrict" model="Model.District" />
</form>
If I use the standard ajax call
``$.ajax({ it works fine
but abp.ajax({ doesn't work
Many thanks
Zak
I am developing a react app using Spring Boot backend.
I am not very friendly with Java or Spring Boot and now I am stuck with an issue.
Bellow is backend method code which is handling the request
#RestController
#RequestMapping("/toys")
public class ToysController {
#Autowired
private ToysService toysService;
#CrossOrigin(origins = "*")
#PostMapping("/addtoy")
public ResponseEntity<Toys> addToy(#RequestParam("file") MultipartFile file,
#RequestParam("toyName") String toyName,
#RequestParam("toyDescription") String toyDescription,
#RequestParam("toyPrice") Long toyPrice,
#RequestParam("quantity") int quantity,
#RequestParam("availability") Boolean availability,
#RequestParam("sellerId") Long sellerId) throws IOException{
Toys toy = new Toys();
toy.setToyName(toyName);
toy.setToyDescription(toyDescription);
toy.setQuantity(quantity);
toy.setToyPrice(toyPrice);
toy.setAvailability(availability);
toy.setSellerId(sellerId);
toy.setToyImage(ImageEncoderDecoder.compressBytes(file.getBytes()));
toy.setImageName(file.getOriginalFilename());
Toys toyRes = toysService.addToy(toy);
if(toyRes!=null) {
toyRes.setToyImage(ImageEncoderDecoder.decompressBytes(toyRes.getToyImage()));
return new ResponseEntity<Toys>(toyRes,HttpStatus.OK);
}
else {
return new ResponseEntity<Toys>(HttpStatus.NO_CONTENT);
}
}
}
Below are the request details I am supposed to use
API: http://localhost:8081/toys/addtoy
Method: POST
Body:
[{"key":"toyName","value":"Car","type":"text","enabled":true},
{"key":"toyDescription","value":"small car 6 month old","type":"text","enabled":true},
{"key":"toyPrice","value":"600","type":"text","enabled":true},
{"key":"quantity","value":"2","type":"text","enabled":true},
{"key":"availability","value":"true","type":"text","enabled":true},
{"key":"file","type":"file","enabled":true,"value":[]},
{"key":"sellerId","value":"1","type":"text","enabled":true}]
Response: Status code 200
Following is how I am trying to hit the API
export const addToy = toy => {
const requestOptions = {
mode: 'cors',
method: 'POST',
headers: {
"Content-Type": "multipart/form-data; boundary=%%",
'Access-Control-Allow-Origin' : '*'
},
body: toy
};
fetch(`${API}/toys/addtoy`, requestOptions) // API = 'http://localhost:8081'
.then(response => {
if(response.status === 200)
console.log('Toy Inserted');
console.log('Resopose : ', response);
})
.catch(err => {
console.log('Error while inserting toy : ', err);
})
}
Calling the above method
const handleSubmit = e => {
e.preventDefault()
let formData = new FormData()
formData.append('toyName', toyName)
formData.append('toyDescription', toyDesc)
formData.append('toyPrice', parseInt(toyPrice))
formData.append('quantity', parseInt(toyQty))
formData.append('availability', parseInt(toyQty) > 0)
formData.append('file', image)
formData.append('sellerId', parseInt(loggedIn.loggedInUser.userId))
addToy(formData)
}
The response I am getting back
body: ReadableStream
locked: false
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: ""
type: "cors"
url: "http://localhost:8081/toys/addtoy"
I have a JSON POST that I'm sending from my Flutter app as soon in the below code:
// class connecting value from the textfield to database with json
class LoginProfile {
int id;
String CardNumber;
String ExpiryDate;
String ExpiryYear;
String VerifyCode;
LoginProfile({this.id = 0,this.CardNumber
,this.ExpiryDate,this.ExpiryYear});
factory LoginProfile.fromJson(Map<String, dynamic> map) {
return LoginProfile(
id: map["id"],
CardNumber: map["CardNumber"],ExpiryDate: map["ExpiryDate"],ExpiryYear: map["ExpiryYear"]
);
}
Map<String, dynamic> toJson() {
return {"id": id,"CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear};
}
#override
String toString() {
return 'Profile{id: $id, "CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear}';
}
}
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: loginProfileToJson(data),
);
if (response.statusCode == 201) {
return true;
} else {
print(response.body);
}
}
I am meant POST my JSON as below:
{
"Registration": {
"CardNumber":"5105105105105100",
"ExpiryDate":"11",
"ExpiryYear":"2023",
"VerifyCode":"123"
}
}
For some reason, I'm unable to make this work and I need to POST "Registration" as the object like it looks above.
Try with jsonEncode
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(loginProfileToJson(data)),
);
if (response.statusCode == 201 || response.statusCode == 200) {
return true;
} else {
print(response.body);
}
I am trying to upload file using AngularJS on client side and Spring RESTApi on server side but getting
Error
org.springframework.web.multipart.MultipartException: The current request is not a multipart request
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.assertIsMultipartRequest(RequestParamMethodArgumentResolver.java:216)
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:167)
.......
[http-bio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - Request method 'POST' not supported
Rest API
Below is a simple Java Post function:
#RequestMapping(method = RequestMethod.POST)
public String saveFile(
#RequestParam("file") MultipartFile file) {
return "success";
}
In Angular, I am using Resource service to send request.
Chrome Developer Tool output
Request Payload
------WebKitFormBoundarydFRgXclyfPVixdHo
Content-Disposition: form-data; name="file"; filename="Release_Notes.txt"
Content-Type: text/plain
------WebKitFormBoundarydFRgXclyfPVixdHo--
Angular Service
function FileUploadService($resource) {
return $resource('/fileUpload/:id', {}, {
'save' : {
method : 'POST',
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
headers['Content-Type'] = undefined;
if (data == undefined) {
return data;
}
var fd = new FormData();
var createKey = function(_keys_, currentKey) {
var keys = angular.copy(_keys_);
keys.push(currentKey);
var formKey = keys.shift()
if (keys.length) {
formKey += "[" + keys.join("][") + "]"
}
return formKey;
};
var addToFd = function(object, keys) {
angular.forEach(object, function(value, key) {
var formKey = createKey(keys, key);
if (value instanceof File) {
fd.append(formKey, value);
} else if (value instanceof FileList) {
if (value.length == 1) {
fd.append(formKey, value[0]);
} else {
angular.forEach(value, function(file, index) {
fd.append(formKey + '[' + index + ']', file);
});
}
} else if (value && (typeof value == 'object' || typeof value == 'array')) {
var _keys = angular.copy(keys);
_keys.push(key)
addToFd(value, _keys);
} else {
fd.append(formKey, value);
}
});
};
addToFd(data, []);
return fd;
}
}
});
}
Any hint to avoid this error?
Method assertIsMultipartRequest from RequestParamMethodArgumentResolver class is called.
The method asserts that it is a post request and content type starts with multipart/
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
Your content type, on the other hand, is
Content-Type: text/plain
And an exception is thrown.
#RequestMapping(method = RequestMethod.POST)
your value attribute is missing in the requestmapping it should be like this
#RequestMapping(value="/fileupload/save/{id}" ,method = RequestMethod.POST)
and use this code when creating angular resource
$resource('fileupload/save/:id',
{id:'1'}, {
save: {method:'POST', params:{charge:true}}
});
in springBoot theres not much to configure when uploading the file.
but you can add these properties to your application property file to change the file size limits.
# File size limit
multipart.maxFileSize = 3Mb
# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb
The above issue is resolved by:
1) Creating a MultipartResolver bean in WebAppConfig.java as shown below:
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
2) Replacing AngularJS FileUploadService (which is using Resource service) with http as shown below:
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
Hope it helps.
I am using ASP.NET MVC 5 for the back-end and Angular + Typescript for the front-end of a web application.
I am trying to upload a file to the server, but for some reason the controller is not getting the file as parameter (the parameter in the controller is null).
I'm sharing below code.
Thanks in advance!
HTML:
<input id="filePath" name="filePath" type="file" accept="image/*" />
<a id="uploadImage" ng-click="ctrl.uploadFile()">Upload</a>
Typescript:
// controller class:
uploadFile(): void {
var filePathInput: any = $("#filePath");
if (filePathInput[0].files) {
var file: any = filePathInput[0].files[0];
var resource: any = this.service.uploadFile();
resource.save(file, (result: any) => {
if (!result || !result.success) {
alert("error");
} else {
alert("ok");
}
});
}
}
// service class:
uploadFile(): ng.resource.IResourceClass<IMyResource> {
return this.$resource("/MyController/UploadImage", null, { method: "POST" });
}
Backend Controller:
[HttpPost]
public JsonResult UploadImage([FromBody]HttpPostedFileBase file)
{
if (file == null || file.ContentLength == 0)
{
return NullParameterResponse();
}
else
{
file.SaveAs("/img/" + Path.GetFileName(file.FileName));
return SuccessResponse();
}
}
TransformRequest function: This makes your request to be sent as a FormData instead as a JSon object.
formDataObject(data: any): any {
var fd = new FormData();
angular.forEach(data, function (value, key) {
fd.append(key, value);
});
return fd;
}
In your angular resource, define the save options and pass the transformRequest function you created earlier.
uploadChequeFile(): ng.resource.IResourceClass<IChequeLoanResource> {
return this.$resource<IChequeLoanResource>("/Cheque/UploadChequeImage", null,
{
save: {
method: "POST",
transformRequest: this.formDataObject,
headers: { 'Content-Type': undefined, enctype: 'multipart/form-data' }
}
});
}
In your controller, just call your save method from the resource passing your file.
var chequeFilePathInput: any = $("#chequeFilePath");
if (chequeFilePathInput[0].files) {
var resource: ng.resource.IResourceClass<services.IChequeLoanResource> = this.uLendService.uploadChequeFile();
resource.save({ "files": chequeFilePathInput[0].files[0] }, (result: any) => {
if (!result || !result.success) {
this.errorMessage = "Error al subir la imagen al servidor. Por favor contáctanos si el error persiste.";
} else {
this.chequeLoan.cheque.filePath = result.message;
this.saveChequeLoan();
}
});
} else {
this.errorMessage = "La imagen del cheque es requerida.";
}
Finally, your controller must receive the IList parameters (with the same name defined in your angular controller)
public JsonResult UploadChequeImage(IList<IFormFile> files)
{
try
{
if (files != null && files.Count > 0)
{
return CreateResponse(true, CreateFile(files[0], #"img\cheques"));
}