Intellij IDEA REST Client file uploading - spring

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

Related

How to support multipart/form-data and application/json by a same method spring boot Rest

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
}

Laravel file upload API using Postman

I have the following code in my controller:
public function upload(Request $request)
{
$files = $request->file('uploads');
if(!empty($files)) {
foreach($files as $file) {
Storage::put($file-getClientOriginalName(),file_get_contents($file));
}
}
Which is called via an api.php in routes:
Route::post('/upload', [ 'uses' => 'UploadController#upload' ]);
I am using postman to test my application.
Header:
Body:
Raw:
POST /scotic/public/api/upload HTTP/1.1 Host: 127.0.0.1:80
Content-Type: multipart/form-data;
boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW Cache-Control: no-cache
Postman-Token: 0caf7349-5c91-e5f1-766f-72a3f1e33900
------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="uploads[]"; filename="banana.png" Content-Type:
image/png png data goes here..
------WebKitFormBoundary7MA4YWxkTrZu0gW--
The $files is empty upon uploading the file. What am i doing wrong?
After a bit of digging, I got my uploader working without postman, I noticed that the '--boundary' was missing from the Content-Type in postman. The LHS works, RHS(postman) does not work.
Any ideas?
The issue was that I was explicitly specifying the Content-Type in postman.
According to one of the answers from this post:
There is no need to add a content-type header manually. You are overriding the value set by Postman. Just select form-data in POST request and send your request to see if it works.

Spring #RequestPart multipart/mixed Object errors

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!

File upload failure on Google Drive API

I'm trying to implement REST client for Google Drive with Jersey 2.0.
According to following document, I made the code that sends files by multipart request.
https://developers.google.com/drive/v2/reference/files/insert
https://developers.google.com/drive/manage-uploads
String targetUrl = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&access_token=" + token.access_token;
WebTarget target = client.target(targetUrl);
final FileDataBodyPart filePart = new FileDataBodyPart("file", file);
final MultiPart multipart = new FormDataMultiPart().field("title", file.getName())
.field("description", file.getName())
.bodyPart(filePart);
Response response = target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multipart, multipart.getMediaType()));
System.out.println("response:" + response.readEntity(String.class));
Here's the POST request by the code.
POST /upload/drive/v2/files?uploadType=multipart&access_token={ACCESS_TOKEN} HTTP/1.1\r\n
Accept: application/json\r\n
Content-Type: multipart/form-data; boundary=Boundary_1_1833261898_1373877178038\r\n
User-Agent: Jersey/2.0 (HttpUrlConnection 1.7.0_25)\r\n
MIME-Version: 1.0\r\n
Host: www.googleapis.com\r\n
Content-Length: 42430\r\n
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "Boundary_1_1833261898_1373877178038"
Type: multipart/form-data
First boundary: --Boundary_1_1833261898_1373877178038\r\n
Encapsulated multipart part: (text/plain)
Content-Type: text/plain\r\n
Content-Disposition: form-data; name="title"\r\n\r\n
Line-based text data: text/plain
Boundary: \r\n--Boundary_1_1833261898_1373877178038\r\n
Encapsulated multipart part: (text/plain)
Content-Type: text/plain\r\n
Content-Disposition: form-data; name="description"\r\n\r\n
Line-based text data: text/plain
Boundary: \r\n--Boundary_1_1833261898_1373877178038\r\n
Encapsulated multipart part: (text/plain)
Content-Type: text/plain\r\n
Content-Disposition: form-data; filename="GoogleDrive.txt"; modification-date="Fri, 12 Jul 2013 08:15:47 GMT"; size=41918; name="file"\r\n\r\n
Line-based text data: text/plain
Last boundary: \r\n--Boundary_1_1833261898_1373877178038--\r\n
My post request was sent but following error occurred.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
Please tell me how to avoid this error.
An upload request should have two multi-parts: metadata and file content and metadata part should be in JSON.
In your case you create a new form-encoded part for each attribute. Use the reference on docs to see the proper formatting: https://developers.google.com/drive/manage-uploads#multipart
final MultiPart multipart = new FormDataMultiPart().field("title", file.getName())
.field("description", file.getName())
.bodyPart(filePart);
Your multipart body should be valid JSON.

How do I make a Multipart request without creating files on the hard disk?

I need to request an http api, the problem is that instead of a common post request where all the parameters are separated by an &, they expect a Multipart request for each one of the parameters like this:
POST /core/eligibility HTTP/1.1
Host: server_host:server_port
Content-Length: 2408
Content-Type: multipart/form-data; boundary=XbCY
--XbCY
Content-Disposition: form-data; name=“PayloadType“
X12_270_Request_005010X279A1
--XbCY
Content-Disposition: form-data; name=“ProcessingMode"
RealTime
--XbCY
Content-Disposition: form-data; name=“PayloadID"
e51d4fae-7dec-11d0-a765-00a0c91e6da6
--XbCY
Content-Disposition: form-data; name=“TimeStamp"
2007-08-30T10:20:34Z
--XbCY
Content-Disposition: form-data; name=“UserName"
hospa
--XbCY
Content-Disposition: form-data; name=“Password"
8y6dt3dd2
--XbCY
Content-Disposition: form-data; name=“SenderID"
HospitalA
--XbCY
Content-Disposition: form-data; name=“ReceiverID"
PayerB
--XbCY
Content-Disposition: form-data; name=“CORERuleVersion"
2.2.0
--XbCY
Content-Disposition: form-data; name=“Payload"
<contents of file go here -- 1674 bytes long as specified above>
--XbCY—
There is a nice question and answer about sending a Multipart request with ruby, the problem is that you have to create a file for each of the parameters, creating like 10 different files for a simple api request is nonsense.
Is there a way to do the same without the need to create a file on disk?
Yes, there is :)
By looking at the gem rest-client, I found that there is a nice parameter called multipart, when its true, all the parameters are sent like a Multipart request.
I.e.:
require 'rest-client'
request_params = {
CORERuleVersion: "value1",
PayloadType: "value2",
ProcessingMode: "value3",
UserName: "value4",
Password: "value5",
SenderID: "value6",
ReceiverID: "value7",
PayloadID: "value8",
TimeStamp: Time.now.utc.iso8601,
Payload: "long_payload",
multipart: true
}
RestClient.post("http://www.example.com", request_params)
It's not possible to tell what your concern is, creating the files because of disk I/O or clutter, or what.
If it's any sort of I/O, you should be able to use Ruby's StringIO class, instead of a regular IO object. Everything is written and read in memory, using strings as buffers.

Resources