I'm trying to insert into a FormData an array of arrays and a string, however java seems to not receive it , I have no log error in my Java server however I have a 500 Internal Server Error in my JavaScript console.
Here is the code for my controller :
#RequestMapping(value = "/getReporting", method = RequestMethod.POST)
#ResponseBody
public void getReporting(#RequestParam RecommendationForm form, #RequestParam String type, HttpServletResponse response) throws ApcException {
System.out.println("prova");
Map.Entry<String, byte[]> result = this.reportingService.getReporting(form,type);
try {
response.setHeader(//
"Content-Disposition",//
"attachment; filename=" +"bobo.xlsx");
response.setContentType("Application/x");
response.getOutputStream().write(result.getValue());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is my service in Angular :
public getExcel(form: FormData): Observable<HttpResponse<Blob>> {
return this.http.post('/SV-AUD/api/reporting/getReporting', form, {observe: 'response', responseType: 'blob'});
}
And the component where I append the info in the formData :
form: FormGroup = this._fb.group(
{
hello1: [],
hello2: [],
hello3: [],
hello4: [],
hello5: [],
hello6: [],
hello7: [],
hello8: [],
hello9: [],
}
);
exportExcel() {
const formData: FormData = new FormData();
formData.append('form', this.form.getRawValue());
if (this.detailedType) {
formData.append('type', 'detailed');
} else {
formData.append('type', 'list');
}
this.reportingService.getExcel(formData).subscribe(data => {
const ctHeader = data.headers.get('content-disposition');
if (ctHeader) {
const filename = ctHeader.split('=')[1];
saveAs(data.body, filename);
}
});
}
The behavior that you are describing suggests that Spring is unable to bind your #RequestParam parameters of your getReporting method to the incoming request.
That means that the data that you are posting from the Angular side does not match up with what is expected on the Spring side.
Unless it's a typo, I'm guessing that the problem is this line in your component's source code, which does nothing (and should be a syntax error due to mis-matched parens):
(this.form.getRawValue()));
I'm guessing that it should be :
formData.append('form', (this.form.getRawValue()));
Related
I have a REACT frontend app and Java Spring backend. I send an image from frontend to backend but REST Controller throws the following error in Java:
java.nio.file.NoSuchFileException: C:\Users\User\AppData\Local\Temp\tomcat.8080.4543654899823294058\work\Tomcat\localhost\ROOT\upload_8189f9b4_9186_424d_b7c4_c4eec0f67e23_00000005.tmp
Controller:
#PostMapping(path="/add", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<Product> addProduct(#ModelAttribute Product product) throws IOException {
...
}
Product Model:
#Document(collection = "products" )
public class Product {
#Id
private String id;
#Field("title")
private String title;
...
#Field("images")
private List<ProductImages> images;
}
I don't even know how to dig it further, what's the issue here?
Images that I send are in multipart FormData with the following structure:
{ data: base64 buffer,
contentType: jpg/png/etc.
}
On the react frontend:
let formData = new FormData();
...
formData.append("images", this.state.images[0]);
...
axios.post(`${server_url}/product/add`,formData)...
This is my JS code to receive a message from Azure Service Bus
function receiveMessage(serviceBusTopic, serviceBusSubscriber, callback) {
serviceBus.receiveSubscriptionMessage(serviceBusTopic, serviceBusSubscriber,
{ isPeekLock: true }, function (error, lockedMessage) {
if (!error) {
try {
const receivedMessage = JSON.parse(lockedMessage.body);
console.log('receivedMessage', receivedMessage);
if (!_.isEqual(receivedMessage.Type, messageType.USERPROFILES_USER_UPDATED)) {
return;
}
//Message received and locked
callback(receivedMessage);
serviceBus.deleteMessage(lockedMessage, function (deleteError) {
if (!deleteError) {
// Message deleted
console.log('message has been deleted.');
}
});
}
catch (error) {
console.log('Start debugging');
console.log(lockedMessage.body);
}
When I receive a message it has strange encoding and JSON.parse throws an exception.
The lockedMessage output is:
{ body: '#\fbase64Binary\b3http://schemas.microsoft.com/2003/10/Serialization/�s\u0002{"Type":"SomeEvent"�\u0001}',
brokerProperties:
{ DeliveryCount: 9,
EnqueuedSequenceNumber: 0,
EnqueuedTimeUtc: 'Thu, 16 Nov 2017 23:50:16 GMT',
LockToken: '6e3e311f-0fe9-4366-844d-18046fd000db',
LockedUntilUtc: 'Fri, 17 Nov 2017 00:10:46 GMT',
MessageId: 'nil',
PartitionKey: '1d84084f-65af-4a33-bb30-62d97d85557d',
SequenceNumber: 61643019899633670,
SessionId: '1d84084f-65af-4a33-bb30-62d97d85557d',
State: 'Active',
TimeToLive: 1566804.069 },
location: '',
contentType: 'application/xml; charset=utf-8',
customProperties: { 'strict-transport-security': NaN, connection: NaN } }
The message is coming from a .NET Core service and that service sends with this code:
var payload = JsonConvert.SerializeObject(SomeEvent);
var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload));
serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
topicClient.SendAsync(serviceBusMessage).Wait();
Why is Node.js not able to parse the message? Another .NET app can receive the same message without any issues.
To avoid this, you need to set ContentType to text/plain when sending a message from .NET Core service. So it should be something like this:
var payload = JsonConvert.SerializeObject(SomeEvent);
var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload))
{
ContentType = "text/plain"
};
serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
topicClient.SendAsync(serviceBusMessage).Wait();
In this article, they explained the problem and the solution for .NET.
Update:
After some diving, this would not happen to me when I either use .NET Core or .NET to send a message with the standard library Microsoft.Azure.ServiceBus whether ContentType is specified or not.
This is my C# code to send a message:
class Program
{
static void Main(string[] args)
{
string connectionString = "Endpoint=sb://...";
var client = new TopicClient(connectionString, "MyTopic");
var payload = JsonConvert.SerializeObject(new DemoMessage() { Title = $"hello core!!! {DateTime.Now}" });
var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload));
serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
client.SendAsync(serviceBusMessage).Wait();
}
private class DemoMessage
{
public DemoMessage()
{
}
public string Title { get; set; }
}
}
This is my Node.js code to receive a message:
var azure = require('azure');
var serviceBusService = azure.createServiceBusService("Endpoint=sb://...");
serviceBusService.receiveSubscriptionMessage('MyTopic', 'sub1', { isPeekLock: true }, function(error, lockedMessage) {
if(!error) {
console.log(lockedMessage);
serviceBusService.deleteMessage(lockedMessage, function (deleteError){
if(!deleteError){
// Message deleted
console.log('message has been deleted.');
}
})
}
});
The lockedMessage output is:
This only happens when I use .NET and the SDK WindowsAzure.ServiceBus with this code:
class Program
{
static void Main(string[] args)
{
string connectionString = "Endpoint=sb://...";
var client = TopicClient.CreateFromConnectionString(connectionString, "MyTopic");
var payload = JsonConvert.SerializeObject(new DemoMessage() { Title = $"hello core!!! {DateTime.Now}" });
var serviceBusMessage = new BrokeredMessage(Encoding.UTF8.GetBytes(payload));
serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
client.Send(serviceBusMessage);
}
private class DemoMessage
{
public DemoMessage()
{
}
public string Title { get; set; }
}
}
Now, the lockedMessage output is:
So, I think the message you received is sent from another .NET client and I suggest you clear all messages from the topic before you test it in Node.js.
I ran into this issue as well. If you are using Stream Analytics then its compatibility level may be the cause of this issue. Stream Analytics compatibility level 1.0 uses an XML serializer producing the XML tag you are seeing. Compatibility level 1.1 "fixes" this issue.
See my previous answer here: https://stackoverflow.com/a/49307178/263139.
I'm making a simple establishment of registration that must have data and a logo. In tests could transmit the file and the data separately but when trying to send them together the following error occurs:
SyntaxError: Unexpected token S
at Object.parse (native)
at qc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:14:245)
at Zb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:76:423)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:77:283
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:7:302)
at Zc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:77:265)
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:78:414)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:112:113
at n.$get.n.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:126:15)
at n.$get.n.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:123:106)
The Angular Controller
angular.module('EntregaJaApp').controller('EstabelecimentoController', ['$scope', '$http','Upload', function($scope, $http,Upload){
$scope.salvar = function(){
Upload.upload({
url: 'http://localhost:8080/site-web/gerencial/estabelecimento/salvar',
file: $scope.picFile[0],
method: 'POST',
headers: {'Content-Type': 'multipart/form-data'}, // only for html5
data: {'estabelecimento': $scope.estabelecimento}
});
}}
The Spring Controller
#Controller
#RequestMapping("/gerencial/estabelecimento")
public class EstabelecimentoController {
#Autowired
private EstabelecimentoService estabelecimentoService;
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
public ResponseEntity<?> salvar(Estabelecimento estabelecimento,#RequestParam(value="file", required=false) MultipartFile file){
try {
byte[] bytes;
if (!file.isEmpty()) {
bytes = file.getBytes();
//store file in storage
}
System.out.println(String.format("receive %s from %s", file.getOriginalFilename(), estabelecimento.getNome()));
estabelecimentoService.salvar(estabelecimento);
return new ResponseEntity<>(MensagensGerais.SUCESSO_SALVAR,HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>((StringUtil.eVazia(e.getMessage()) ? MensagensGerais.ERRO_CONSULTAR : e.getMessage()),HttpStatus.BAD_REQUEST);
}
}
}
did you missed the return type annotation? Like
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
#Produces(MediaType.APPLICATION_JSON)
public ResponseEntity<?> salvar(Estabelecimento estabelecimento,#RequestParam(value="file", required=false) MultipartFile file){...}
Assuming that the request specifies an Accept Header "application/json", it seems that the Strings are not correctly serialized (by Spring?). Angular versions prior to 1.3.x seem to have been generous, but now an exception is thrown when the response is not correct JSON. I have added the following response transformer to my app:
$httpProvider.defaults.transformResponse.unshift(function(data, headersGetter, status){
var contentType = headersGetter('Content-Type');
if(angular.isString(contentType) && contentType.startsWith('application/json')){
try {
angular.fromJson(data);
} catch(e){
var mod = '"'+data+'"';
try {
angular.fromJson(mod);
return mod;
}
catch(e){
return data;
}
}
return data;
}
else{
return data;
}
});
It transforms a JS string to a JSON string object by wrapping it in additional ".
I have a layout page that has a form with AntiForgeryToken
using (Html.BeginForm(action, "Account", new { ReturnUrl = returnUrl }, FormMethod.Post, new { Id = "xcrf-form" }))
This generates a hidden field
<input name="__RequestVerificationToken" type="hidden" value="p43bTJU6xjctQ-ETI7T0e_0lJX4UsbTz_IUjQjWddsu29Nx_UE5rcdOONiDhFcdjan88ngBe5_ZQbHTBieB2vVXgNJGNmfQpOm5ATPbifYE1">
In my angular view (that is loaded in a div in the layout page, I do this
<form class="form" role="form" ng-submit="postReview()">
And my code for postReview() is as follows
$scope.postReview = function () {
var token = $('[name=__RequestVerificationToken]').val();
var config = {
headers: {
"Content-Type": "multipart/form-data",
// the following when uncommented does not work either
//'RequestVerificationToken' : token
//"X-XSRF-TOKEN" : token
}
}
// tried the following, since my other MVC controllers (non-angular) send the token as part of form data, this did not work though
$scope.reviewModel.__RequestVerificationToken = token;
// the following was mentioned in some link I found, this does not work either
$http.defaults.headers.common['__RequestVerificationToken'] = token;
$http.post('/Review/Create', $scope.reviewModel, config)
.then(function (result) {
// Success
alert(result.data);
}, function (error) {
// Failure
alert("Failed");
});
}
My MVC Create method is as follows
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult Create([Bind(Include = "Id,CommentText,Vote")] ReviewModel reviewModel)
{
if (User.Identity.IsAuthenticated == false)
{
// I am doing this instead of [Authorize] because I dont want 302, which browser handles and I cant do client re-direction
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
// just for experimenting I have not yet added it to db, and simply returning
return new JsonResult {Data = reviewModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
So no matter where I put the token, no matter what I use for 'Content-Type' (I tried application-json and www-form-urlencoded) I always get the error "The required anti-forgery form field "__RequestVerificationToken" is not present."
I even tried naming __RequestVerificationToken and RequestVerificationToken
Why does my server not find the damn token?
I also looked at couple of links that ask you to implement your own AntiForgeryToeknVerifyAttrbute and verify the token that is sent as cookieToken:formToken, I have not tried that but why I am not able to get it working whereas this works for the MVC controllers (non-angular posts)
Yes. By default, MVC Framework will check for Request.Form["__RequestVerificationToken"].
Checking the MVC source code
public AntiForgeryToken GetFormToken(HttpContextBase httpContext)
{
string value = httpContext.Request.Form[_config.FormFieldName];
if (String.IsNullOrEmpty(value))
{
// did not exist
return null;
}
return _serializer.Deserialize(value);
}
You need to create your own filter to check it from Request.Header
Code Snippet from Phil Haack's Article - MVC 3
private class JsonAntiForgeryHttpContextWrapper : HttpContextWrapper {
readonly HttpRequestBase _request;
public JsonAntiForgeryHttpContextWrapper(HttpContext httpContext)
: base(httpContext) {
_request = new JsonAntiForgeryHttpRequestWrapper(httpContext.Request);
}
public override HttpRequestBase Request {
get {
return _request;
}
}
}
private class JsonAntiForgeryHttpRequestWrapper : HttpRequestWrapper {
readonly NameValueCollection _form;
public JsonAntiForgeryHttpRequestWrapper(HttpRequest request)
: base(request) {
_form = new NameValueCollection(request.Form);
if (request.Headers["__RequestVerificationToken"] != null) {
_form["__RequestVerificationToken"]
= request.Headers["__RequestVerificationToken"];
}
}
public override NameValueCollection Form {
get {
return _form;
}
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,
AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute :
FilterAttribute, IAuthorizationFilter {
public void OnAuthorization(AuthorizationContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
var httpContext = new JsonAntiForgeryHttpContextWrapper(HttpContext.Current);
AntiForgery.Validate(httpContext, Salt ?? string.Empty);
}
public string Salt {
get;
set;
}
// The private context classes go here
}
Check out here for MVC 4 implementation, to avoid salt issue
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,
AllowMultiple = false, Inherited = true)]
public sealed class ValidateJsonAntiForgeryTokenAttribute
: FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
var httpContext = filterContext.HttpContext;
var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
AntiForgery.Validate(cookie != null ? cookie.Value : null,
httpContext.Request.Headers["__RequestVerificationToken"]);
}
}
I had the same problem. Turned out that I don't need to set antiforgery token anywhere explicitly in my angular js code. The MVC controller expects this token value to be delivered from 1. the form field, 2. cookie. The filter equates and is happy when they match.
When we submit the form, hidden field for the anti forgery token automatically supplies its value. Cookie is automatically set by the browser. So as I said, we don't need to do anything explicitly.
The problem really is request's content-type. By default it goes as as application/json and therefore the a.f. token value (or rather any form data) is not received.
Following worked for me:
// create the controller
var RegisterController = function ($scope, $http) {
$scope.onSubmit = function (e) {
// suppress default form submission
e.preventDefault();
var form = $("#registerform");
if (form.valid()) {
var url = form.attr('action');
var data = form.serialize();
var config = {
headers: {
'Content-type':'application/x-www-form-urlencoded',
}
};
$http.post(url, data, config).success(function (data) {
alert(data);
}).error(function(reason) {
alert(reason);
});
}
};
};
As Murali suggested I guess I need to put the toekn in the form itself, so I tried putting the token as part of form data and I needed to encode the form data as explained in https://stackoverflow.com/a/14868725/2475810
This approach does not require any additional code on server side, also we do not need to create and join cookie and form token. Just by form-encoding the data and including token as one of the fields as explained in the answer above we can get it rolling.
You should perform the HTTP request in this way:
$http({
url: '/Review/Create',
data: "__RequestVerificationToken=" + token + "¶m1=1¶m2=2",
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(result) {
alert(result.data);
}).error(function(error) {
alert("Failed");
});
I have a method which save an image file in the database as a BLOB file. The method works fine, but when I get the callback in ExtJS filefield component, it always goes through failure function and I don't know what I have to respond to go through success function, this is my code:
Server method:
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces({ MediaType.APPLICATION_JSON })
public ServiceResponse uploadFile(#QueryParam("id") Long iconId, FormDataMultiPart form) {
CatIcon icon;
if (iconId != null) {
icon = catIconBean.getOne(iconId);
} else {
icon = new CatIcon();
}
byte[] image = form.getField("iconBmp").getValueAs(byte[].class);
if (image.length != 0) {
MultivaluedMap<String, String> headers = form.getField("iconBmp").getHeaders();
String type = headers.getFirst("Content-type");
List<String> list = Arrays.asList("image/gif", "image/png", "image/jpg", "image/jpeg",
"image/x-icon", "image/bmp");
if (list.contains(type)) {
icon.setIconBmp(image);
icon.setType(type);
}
}
icon.setDescription(form.getField("description").getValue());
icon.setFileName(form.getField("fileName").getValue());
icon = catIconBean.saveIcon(icon);
ServiceResponse sr = new ServiceResponse();
sr.httpResponse = true;
return sr;
}
What I have to return in the code above?
Client:
uploadIcon : function(item, e, eOpts) {
var me = this;
var form = this.getDetail().getForm();
var valid = form.isValid();
if (!valid) {
return false;
}
var values = form.getValues();
if(values) {
form.submit({
url : myApplication.defaultHost() + 'icon/upload?id=' + values.id,
waitMsg : 'Uploading...',
success : function(form, action) {
me.onCompleteSaveOrDelete();
},
failure : function(form, action) {
me.onCompleteSaveOrDelete();
}
});
}
},
I write the same function, me.onCompleteSaveOrDelete(), in both callback functions to make it be called, that's the method which I want to be called in success.
Greetings.
UPDATE:
I did almost the same Alexander.Berg answered. The only difference was that I write #Produces({ MediaType.APPLICATION_JSON }) instead of #Produces({ MediaType.TEXT_HTML }), because I need Json Response. But when I debug in chrome and check the response, I get this:
In failure:
failure : function(form, action) {
me.onCompleteSaveOrDelete();
}
In action param, within responseText:
"{"data":"{\"success\":true}","httpResponse":true,"totalCount":0}"
But It's still going through failure...I think I'm very close, any help??
Greetings.
The fileupload in Extjs is more tricky, because it is using iframe and submit, not a real ajax request for uploading files.
Try this on Server method:
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_HTML)
public String uploadFile(#QueryParam("id") Long iconId, FormDataMultiPart form) {
(...)
JSONObject json = new JSONObject();
json.put("success", true);
json.put("msg", "Success");
return json.toString();
}
this is because the upload accepts Content-Type text/html,
see Example at http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.field.File -> Example Usage -> Live Preview
Use Firefox browser with Firebug plugin and on Net tab the following URL -> http://docs.sencha.com/extjs/4.2.2/photo-upload.php
Response Headersview source
(...)
Content-Type text/html
(...)
Request Headersview source
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
(...)