I am fairly new to angular and i am trying to send a name and image file to my server which is written in rails. But the data i am being received on my server is not correct and i have tried many fixes but nothing seems to be working. The request payload that being sent is this
-----WebKitFormBoundaryhRvQy5dRArcb6BfP
Content-Disposition: form-data; name="project[logo]"; filename="badge.png"
Content-Type: image/png
------WebKitFormBoundaryhRvQy5dRArcb6BfP
Content-Disposition: form-data; name="project[name]"
abc
------WebKitFormBoundaryhRvQy5dRArcb6BfP--
This is not being accepted in rails server and returns me a bunch of gibberish in the console/log
��2˾F
2ƺx���;p}}�0���'�C�F
��b7�Ӡ�}��c��Ii���W8��I#�<dy���}4�|���{c��5�iV�#�����*�����'��
:ظ�<+�I5��^��ԓk�qi���R91R��pi7QZϢ�����V�m��� �(��8�m�c%OGN#�k��k2�>_O�����^Ya��+�����1������^�����K�3�07q���{7�ܶ0+��&sZ����w7�>f�^��A�/����d�����g�i�
PG?_��u�����5�i2��F$��\7(�ԟ�t8e9�3�9=Lk�#��ֽ��3��%FJ�QjI����f���qmI4֍4�^��P|�S���)Ԋ0Җ�AEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE�����͊O6c��>y?횜����5�Z��Nuf��qr}ݶK�N�K�k̨BU'E^Ri/�W���G/�C�W?f��
RT������ׯ!�8a\�z�_^���Z�ݺEm�(��|��GJ�iS�8�k�{��ۻ��#��+"(��(�`��+��(��(��(��$��"��
2:�V��G��j���K`�S�LI���s�C�����+�����-h)[��q�
��/�^洫T��NMw[�^�z?]���%��ki
z�ͭ��f+��T��a���� S��H:��dz���{2���5
���A#���qڇ��t�D�D2LGz�q��`��nM|�/)�B�z���K��^p__�
���
This is my service.ts
postCreateProject(logo, name)
{
const formData: FormData = new FormData();
const url = EndPoints.BASE_URL + EndPoints.Projects;
formData.append('project[logo]', logo);
formData.append('project[name]', name)
console.log(formData.get('project[logo]'))
return this.httpService.postFileUpload(url, formData);
This is my postFileUpload in the httpService
postFileUpload(url: string, fmd: FormData): Observable<any> {
console.log('post file upload')
const headers = new HttpHeaders();
headers.append('Form-Data','FileUpload');
// headers.set('Content-Type', 'multipart/form-data');
// headers.set('Accept', 'application/json');
return this.http.post(url, fmd, {headers : headers});
}
If you need additional files please ask. Thanks for helping.
If you're using rails 5+ and angular 4+, you might try excluding the headers and just having
return this.http.post(url, fmd).
That's what I do (rails 6 with angular 10) and the data on the rails end is correct.
Related
I am trying to upload an image (MultipartFile) using RestTemplate to a server URL.
Sending request from postman works with Content-Type: image/jpg and an image sent as Binary File from Body.
Method implementation in SpringBoot:
public ResponseEntity<String> uploadImage(MultipartFile file) {
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
restTemplate.getMessageConverters().add(new BufferedImageHttpMessageConverter());
LinkedMultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, httpHeaders);
return restTemplate.exchange(UPLOAD_URL, HttpMethod.POST, requestEntity, String.class);
Exception:
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [image/jpeg]
Upload works with Content-Type MediaType.MULTIPART_FORM_DATA but REST Service that I use only accepts image/jpg as HTTP Content-Type.
Thanks.
Your remote service accept image/jpg so you should stream byte instead of multi-part:
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpeg");
Resource res = new InputStreamResource(file.getInputStream());
HttpEntity<Resource> entity = new HttpEntity<>(res, headers);
template.exchange(UPLOAD_URL, HttpMethod.POST, entity , String.class);
The RestTemplate has ResourceHttpMessageConverter which streams your multi-part to the service for you.
I send some data from client side using POST request
var value = new Map<String, String>();
value["param1"] = 'value1';
value["param2"] = 'value2';
value["param3"] = 'value3';
HttpRequest.postFormData('http://localhost:8080/', value);
and try to get this data on the server side:
HttpServer.bind(InternetAddress.ANY_IP_V6, 8080).then((server) {
server.listen((HttpRequest request) {
//TODO: process POST request
});
});
But how can I get POST values from the request as Map< string, string>?
upd 1
But as I see result of
var jsonString = await request.transform(UTF8.decoder).join();
depends on type of post message. If I change it result will be
multipart/form-data
------WebKitFormBoundaryoQQD7N0iA5zS8qmg
Content-Disposition: form-data; name="param1"
value 1
------WebKitFormBoundaryoQQD7N0iA5zS8qmg
Content-Disposition: form-data; name="param2"
value 2
------WebKitFormBoundaryoQQD7N0iA5zS8qmg
Content-Disposition: form-data; name="param3"
value 3
------WebKitFormBoundaryoQQD7N0iA5zS8qmg--
text/plain
param1=value 1
param2=value 2
param3=value 3
application/x-www-form-urlencoded
param1=value+1¶m2=value+2¶m3=value+3
As I have already asked how can I convert it to Map< string, string>?
Here is a complete tutorial https://www.dartlang.org/docs/tutorials/httpserver/#handling-post
String jsonString = await request.transform(UTF8.decoder).join();
or
Map result = await request.transform(UTF8.decoder).join().then(JSON.decode);
I have the same question, and I didn't find any solution until now. I need to pass a map from client to server, and server to use that map to interrogate a mongodb database. Client send that map, but server receive a string. Any conversion to json return also string, not a map.
On the client side I send a map named query:
await HttpRequest.postFormData('http://localhost:8085/$_coll',query).then((HttpRequest response)
On the server side :
if (request.method == 'POST') {
query = await request.transform(utf8.decoder).join();
}
I've tried to encode/decode to json, but with no success.
I have a problem using HTTPBuilder in Grails.
The code is something like this.
def http = new HTTPBuilder("theURL")
http.request(method, ContentType.JSON) {
uri.path = "theURI"
headers.'Authorization' = "OAuth $accessToken"
headers.'Accept' = "application/json"
headers.'content-type' = "application/json;charset=utf-8"
response.success = { resp, json ->
result = json
}
}
return result
Now the response is a JSON with "Cobro N�� 1234" but i need "Cobro Nº 1234"
I tried this with curl and the response is fine "Cobro Nº 1234", this made me think that the problem is the HTTPBuilder and not my API who response the request.
I think that it is a problem with the response encoding.
http.encoders.charset = Charsets.UTF_8
Try this:
headers.'content-type' = "application/JSON;charset=UTF-8" //capitalized
Either, try this:
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
Try adding this after your 'http' declaration:
http.encoderRegistry = new EncoderRegistry( charset: 'utf-8' )
I couldn't follow if the content you are sending needs to be encoded with UTF-8, or if the content you are receiving needs to be read with UTF-8.
I was having a problem sending content with UTF-8, and this is what I did.
http.request(Method.PUT) { request ->
// set headers here
request.entity = new StringEntity(json.toString(), "UTF-8")
}
I'm converting a net.sf.json.JSONObject to a String in order to pass it along as the body of the PUT call. I'm using StringEntity, and previously I wasn't setting the encoding on the StringEntity, but there is a constructor that takes an encoding. Now that I'm setting "UTF-8" there, it is working.
I have an ASP.net application that allows the users to report bugs and attach files. The bug together with its detail and attachments should be saved in FogBugz.
I have managed to create everything except the file attachment part.
here is my code:
private void NewCaseWithFile()
{
string fbUrl = "https://test.fogbugz.com/api.asp";
string fbToken = logInFogBugz();
string param = "";
param += "cmd=new";
param += "&token=" + fbToken;
param += "&sTags=" + "OnlineService,";
param += "&sTitle=" + "Testing";
param += "&sEvent=" + "This case is being created from Visual Studio";
param += "&nFileCount=" + "1";
param += "&File1=" + "Picture.png";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(fbUrl + "?" + param);
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.ContentType = "multipart/form-data";
httpWebRequest.Accept = "application/xml";
httpWebRequest.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
XDocument doc = XDocument.Load(streamReader);
}
I have tried all instructions under "Editing Cases" but it did not help. In fact I have no idea what are File 1, File 2 and how to send them to FogBugz.
Can anyone help me with this?
Many thanks!
File1 should be specified in the body of your multipart/form-data post (not as a querystring parameter).
You actually have to specify all the bytes in the file.
There's an answer on fogbugz.stackexchange.com as well as a C# FogBugz API wrapper that will handle all the parts for you.
The form parts in the body of your post would look like
--sdfjdsjsdflk SOME BOUNDARY--
Content-Disposition: form-data; name="File1"; filename="foo.jpg"
Content-Transfer-Encoding: base64
Content-Type: image/png
slfkajdflksjflajfdj
sldfjsd;aljfds
these are actual data bytes from the foo.jpg file
slfkjdsfljds
sdflajsdfs
Or you can look at this question which points to an RFC with an example.
According to its documentation, GM_xmlhttpRequest should be able to take a data parameter as part of its argument.
However, I can't seem to get it to work.
I have a simple server that echoes the parameters given to it:
require 'sinatra'
require 'json'
get '/' do
JSON.dump params
end
post '/' do
JSON.dump params
end
And a simple greasemonkey script that just tries to POST some data to the server.
It tries to pass data as query parameters in the URL and as postdata:
// ==UserScript==
// #name PostDataTest
// #namespace Test
// #description Simple test of GM_xmlhttpRequest's data parameter
// #include http://localhost:4567/
// #version 1
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// #grant metadata
// #grant GM_xmlhttpRequest
// ==/UserScript==
var url = '/?q0=0&q1=1';
var data = 'd0=0&d1=1'
GM_xmlhttpRequest({ method: 'POST', url: url, data: data, onload: function(r){
console.log('gm:' + r.responseText);
}});
$.post(url, data, function(d,s,r){
console.log('jq:' + r.responseText);
});
When I POST postdata using jQuery, it works fine, but any postdata I POST using GM_xmlhttpRequest is ignored:
jq:{"q0":"0","q1":"1","d0":"0","d1":"1"}
gm:{"q0":"0","q1":"1"}
This leads me to believe that GM_xmlhttpRequest isn't actually using the data parameter I'm giving it. (I'm not sure b/c I can't monitor GM_xmlhttpRequest's network activity in Firebug).
What's going on here? Did I screw something up? Did the API shift? How can I use GM_xmlhttpRequest to post data without packing it into the URL?
Ok, I used the TamperData firefox add-on to monitor my GM_xmlhttpRequests (which were sending the postdata) to see what they were doing differently.
The difference was four headers. Where jQuery sent
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:4567/
GM_xmlhttpRequest sent:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type: text/plain; charset=UTF-8
Using the headers: parameter I was able to specify the Content-Type of my GM_xmlhttpRequest, which got it to work.
// ==UserScript==
// #name PostDataTest
// #namespace Test
// #description Simple test of GM_xmlhttpRequest's data parameter
// #include http://localhost:4567/
// #version 1
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// #grant metadata
// #grant GM_xmlhttpRequest
// ==/UserScript==
var url = '/?q0=0&q1=1';
var data = 'd0=0&d1=1'
GM_xmlhttpRequest({
method: 'POST',
url: url+'gm',
data: data+'gm',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
onload: function(r){
console.log('gm:' + r.responseText);
}});
$.post(url+'jq', data+'jq', function(d,s,r){
console.log('jq:' + r.responseText);
});