I'm currently using Wicket and a jQuery plugin to crop picture ("croppic") and it need to request with ajax my back-end to crop the picture. The data are sent in a multipart format.
My Wicket back-end is an Ajax behavior with the "onRequest" method and I don't know how to retrieve the multipart data.
#Override
public void onRequest() {
String json = "{}";
boolean hasError = false;
RequestCycle cycle = getComponent().getRequestCycle();
IRequestParameters parameters = cycle.getRequest().getPostParameters();
This code only access to classic POST variables but cannot used to multipart form data (values are empty).
Do you know how to proceed for that?
PS: this thread is helpful but not understandable for me : Wicket 6 - Capturing HttpServletRequest parameters in Multipart form?
The body payload:
------WebKitFormBoundarykpVsQAYFGJywlAZd
Content-Disposition: form-data; name="imgUrl"
https://scontent.xx.fbcdn.net/hprofile-xpf1/t31.0- 1/c0.0.1536.1536/13055008_225242101175595_5770204993752392511_o.jpg
------WebKitFormBoundarykpVsQAYFGJywlAZd
Content-Disposition: form-data; name="imgInitW"
1536
------WebKitFormBoundarykpVsQAYFGJywlAZd
Content-Disposition: form-data; name="imgInitH"
1536
------WebKitFormBoundarykpVsQAYFGJywlAZd
Content-Disposition: form-data; name="imgW"
500
------WebKitFormBoundarykpVsQAYFGJywlAZd
Content-Disposition: form-data; name="imgH"
500
------WebKitFormBoundarykpVsQAYFGJywlAZd
Content-Disposition: form-data; name="imgY1"
etc...
Try with:
WebRequest webRequest = (WebRequest) cycle.getRequest();
MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
multiPartRequest.parseFileParts();
IRequestParameters params = multiPartRequest.getRequestParameters();
Here is my final code that works... very ugly but it works properly.
#Override
public void onRequest() {
boolean hasError = false;
IRequestParameters parameters = null;
RequestCycle cycle = RequestCycle.get();
ServletWebRequest webRequest = (ServletWebRequest) cycle.getRequest();
try {
MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(Bytes.kilobytes(10), "ignored");
multiPartRequest.parseFileParts();
parameters = multiPartRequest.getRequestParameters();
} catch (FileUploadException e) {
hasError = true;
}
After that you can easily call :
parameters.getParameterValue("you_param");
Related
I have a POST method that needs to support both multipart/form-data and application/json.
i.e. consumes = { MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE }
When I'm supporting Multipart request, I need a multipart file and a multipart json which can be obtained by declaring as below:
Line 1-> #RequestPart("file") MultipartFile file, #RequestPart("jsonString") InputJsonVO inputJsonVO
Similarly when supporting an application/json, I need to accept the whole body as a Json content:
Line 2 -> #RequestBody InputJsonVO inputJsonVO
It works fine when we have either line 1 or line 2, but not both in the same method as parameters.
`#PostMapping(path = "/multipart", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public String getMessage(#RequestPart(required=false, name="file") MultipartFile file, #RequestPart(required=false, name="jsonString") InputJsonVO inputJsonVO,
#RequestBody(required=false) InputJsonVO inputJsonVO2
)`
With this method declaration if I send a POST request:
POST /multipart HTTP/1.1
Host: localhost:8080
content-type: application/json
Content-Length: 335
<A Valid Json>
This works fine.
But when I sent a POST request as below from postman, it doesn't work:
POST /multipart HTTP/1.1
Host: localhost:8080
Content-Length: 650
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="/C:/Users/sdamarla/Downloads/J867FE94.jpeg"
Content-Type: image/jpeg
(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="jsonString"
Content-Type: application/json
<A valid Json>
----WebKitFormBoundary7MA4YWxkTrZu0gW
Gives below error:
Content type 'multipart/form-data;boundary=--------------------------335202067624768397899751' not supported]
Note: multipart request is working fine when removing the #RequestBody and the corresponding parameter.
Please let me know if this is a valid use case and if so where am I failing.
Just define two different methods, one for each representation:
#PostMapping(path = "/multipart", consumes = MediaType.APPLICATION_JSON_VALUE)
public String getMessage(#RequestBody InputJsonVO inputJsonVO) {
getMessage(null, inputJsonVO);
}
#PostMapping(path = "/multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String getMessage(#RequestPart MultipartFile file, #RequestPart InputJsonVO inputJsonVO) {
// your code here
}
I was trying to upload Multipart/form-data on Android using Okhttp, but it does not work.
The request header is
POST /api/texttospeech/v3.0-beta1//datasets/upload HTTP/1.1
Host: koreacentral.customvoice.api.speech.microsoft.com
Connection: keep-alive
Content-Length: 201455
Accept: application/json, text/plain, /
Correlation-Id: 290c5850-f621-11ea-ac4a-9dac0e19cc7b
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36 Edg/85.0.564.51
Ocp-Apim-Subscription-Key: 38fae10960fc477ba614c6dfe64613ba
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryZAaHsREIpzJ9sBHS
Origin: https://speech.microsoft.com
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Accept-Encoding: gzip, deflate, br
Accept-Language: ko,en;q=0.9,en-US;q=0.8
and the multipart/form-data is
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="projectId"
1a685f5d-400b-4801-8adb-9d359cad27cb
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="name"
16151
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="description"
51561
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="dataImportKind"
CustomVoice
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="locale"
en-US
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="properties"
{"Gender":"Male","IsMixLingual":"false","PortalAPIVersion":"3"}
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="audiodata"; filename="1.zip"
Content-Type: application/x-zip-compressed
------WebKitFormBoundaryZAaHsREIpzJ9sBHS
Content-Disposition: form-data; name="transcriptions"; filename="transcript.txt"
Content-Type: text/plain
------WebKitFormBoundaryZAaHsREIpzJ9sBHS--
The code I created is something like this.
String boundary = "----WebKitFormBoundary" + result; //result is the random digits
String Url = String.format("https://%s.customvoice.api.speech.microsoft.com/api/texttospeech/v3.0-beta1//datasets/upload", region);
String audioPath = getFilesDir().getAbsolutePath()+"/audios.zip";
String scriptPath = getFilesDir().getAbsolutePath()+"/script.txt";
System.out.println("properties to String"+ properties.toString());
File audioFile = new File(audioPath);
File scriptFile = new File(scriptPath);
//Create request body (params or json)
System.out.println("audiopath is " + audioPath);
System.out.println("scriptpath is "+ scriptPath);
MultipartBody formBody = new MultipartBody.Builder(boundary)
.setType(MultipartBody.FORM)
.addFormDataPart("projectId", projectId)
.addFormDataPart("name", defaultVal)
.addFormDataPart("description", defaultVal)
.addFormDataPart("dataImportKind", "CustomVoice")
.addFormDataPart("locale", "en-US")
.addFormDataPart("properties", properties.toString())
.addFormDataPart("audiodata", "audios.zip", RequestBody.create(MediaType.parse("application/x-zip-compressed"), audioFile))
.addFormDataPart("transcriptions", "script.txt", RequestBody.create(MediaType.parse("text/plain"), scriptFile))
.build();
System.out.println(formBody);
Request request = new Request.Builder()
.header("Ocp-Apim-Subscription-Key", subKey)
.addHeader("Ocp-Apim-Subscription-Key", subKey)
.addHeader("Content-Type", formBody.contentType().toString())
.post(formBody)
.url(Url)
.build();
System.out.println("Data upload request : "+ request);
System.out.println("Data upload request : "+ request.body());
System.out.println("Data upload request : "+ request.body().toString());
//Response response = client.newCall(request).execute();
//System.out.println("data upload response "+response.body().string());
//response.close();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
System.out.println("Response "+response);
}
});
return null;
}
The error is
Response{protocol=http/1.1, code=500, message=Internal Server Error, url=https://koreacentral.customvoice.api.speech.microsoft.com/api/texttospeech/v3.0-beta1//datasets/upload}
The Internal Server Error seems to be wrong, since it works if I send the request through Python, using
from requests_toolbelt.multipart.encoder import MultipartEncoder
Code 500 means the server receives your request but fail to complete it.As the server performs well while using python according to your description, I guess that you got something wrong in your HTTP-Header or multipart/form-data.But it cannot be find out yet by the only info.I suggest that you should compare the data you send through okhttp and python to find out the difference.
I'm trying to upload a xlsx file to server, but I receive two different errors, whether I specify the contentType in the http request header or not. If I specify "Content-type: multipart/form-data" I get the following error:
FileUploadException: the request was rejected because no multipart
boundary was found
Then, if I do not specify the content type (as proposed in different answers), I get this error:
current request is not a multipart request
This is what I do to upload the file. HTML (input fired by a button that calls an uploadFile() method):
<input type="file" #fileUpload id="fileUpload" name="fileUpload" accept=".xlsx" style="display:none;" />
.ts:
uploadFile() {
const fileUpload = this.fileUpload.nativeElement;
fileUpload.onchange = () => {
this.file = fileUpload.files[0];
this.uploadFileToServer();
};
fileUpload.click();
}
uploadFileToServer() {
const formData = new FormData();
formData.append('file', this.file);
this.importService.uploadFile(formData).subscribe(d => {
});
}
In the service the method does this:
this.http.post(
apiUrl,
formData,
options
);
where in options there are the specified headers:
let applicationHeaders = new HttpHeaders();
applicationHeaders = applicationHeaders.append('Content-type', 'multipart/form-data');
multipart or blank.
In the POST request in the request payload I have:
------WebKitFormBoundarytNckytdr7I8wQcuc
Content-Disposition: form-data; name="file"; filename="Template (2).xlsx"
Content-Type: application/octet-stream
------WebKitFormBoundarytNckytdr7I8wQcuc--
I am trying to upload file through Intellij IDEA REST Client. I choose "File to upload (multipart/form-data)" and choose file to send. What is parameter name of this file? In my Sprint Controller i use this code
#RequestMapping(method = RequestMethod.POST, value = "/{id}/photo")
public void setCover(#PathVariable int id,
#RequestParam MultipartFile file) {
System.out.println(file.getName());
}
I also tried different names, such as "file", "fileToSend", "File to send" for #RequestParam, but Spring always cant find MultipartFile paramater.
I use the following code which works for me:
POST http://localhost:9003/goods/add HTTP/1.1
Content-Type: multipart/form-data; boundary=boundary
--boundary
Content-Disposition: form-data; name="file"; filename="file.csv"
// The 'input.txt' file will be uploaded
< /Users/xing/Desktop/file.csv
--boundary
Content-Disposition: form-data; name="advertType"
1
--boundary
// The method in the Spring controller
public Xxxx add(#RequestParam("file") MultipartFile file, Long advertType) {
For more information, please refer to https://www.jetbrains.com/help/ruby/exploring-http-syntax.html#use-multipart-form-data
File upload is not allowed due to security concern, not for application running on local machine. This solution worked for me. Its based on the comment by vincent.
See below:
POST http://localhost:8080/api/test HTTP/1.1
Content-Type: multipart/form-data; boundary=WebAppBoundary
--WebAppBoundary
Content-Disposition: form-data; name="param1"; filename="myfile.csv"
Content-Type: application/csv
// below will the path to the file (i.e. myfile.csv)
< C:/users/user/data/sample/myfile.csv
--WebAppBoundary
Content-Disposition: form-data; name="param2"
// value of param2
test
--WebAppBoundary
###
If you wish to do multipart file uploads inside IntelliJ IDEA's REST Client, please upvote this bug report => https://youtrack.jetbrains.com/issue/WEB-20197
I am attempting to upload a file with additional parameters using RequestParts. I have the file uploading correctly; however, when I try and add in the additional parameters I get an error in response.
My Controller:
#RequestMapping(value = "/v1/cases/{caseId}/file", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public Success uploadFile(
#RequestPart(value="file") MultipartFile file,
#RequestPart(value="fileParameters") FileParameters fileParameters) throws FileNotFoundException, IOException {
I have tried to POST to this 2 different ways with different errors:
1)
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParameters"
{"filePassword":"testPassword", "configuration":{}, "target":null}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
this errors with:
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. See 'supportedMediaTypes' in 'additionalInfo' for a list of supported types
2)
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="myFile"
Content-Type:
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[filePassword]"
testPassword
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[configuration]"
{}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="fileParamters[target]"
null
----WebKitFormBoundaryE19zNvXGzXaLvS5C
which returns the following error:
"rootExceptionClass": "org.springframework.web.multipart.support.MissingServletRequestPartException",
"rootExceptionMessage": "Required request part 'keyParameters' is not present."
I'm assuming the first approach is the correct one; however, the application does support JSON, so I'm not sure what I am missing configuration wise. Is there something I have to add to the request for this to work correctly, or am I missing something in a message converter.
Note: Not sure this matters but I am using Postman to test the endpoint.
add
Content-Type: application/json;
under the line of
Content-Disposition: form-data; name="fileParameters"
to explicit how to resolve your parameters
see spring docs here
I have met the same issue with you! I changed the #RequestPart to #Multipart, the issue was fixed. hope it can help for you!