Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices
Convert an array of objects to array of the objects' values
Can a space-faring robot still function over a billion years?
ESPP--any reason not to go all in?
Create chunks from an array
Has a sovereign Communist government ever run, and conceded loss, on a fair election?
When to use the term transposed instead of modulation?
How to chmod files that have a specific set of permissions
Is this nominative case or accusative case?
Are there other characters in the Star Wars universe who had damaged bodies and needed to wear an outfit like Darth Vader?
What does "rhumatis" mean?
How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?
Can a Mimic (container form) actually hold loot?
A bug in Excel? Conditional formatting for marking duplicates also highlights unique value
What is Tony Stark injecting into himself in Iron Man 3?
Iron deposits mined from under the city
Why would the IRS ask for birth certificates or even audit a small tax return?
How can I be pwned if I'm not registered on the compromised site?
Dukha vs legitimate need
PTiJ: How should animals pray?
Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?
Should I use HTTPS on a domain that will only be used for redirection?
Short story about an infectious indestructible metal bar?
Can a Mexican citizen living in US under DACA drive to Canada?
Does the US political system, in principle, allow for a no-party system?
Posting a File and Associated Data to a RESTful WebService preferably as JSON
2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices
This is probably going to be a stupid question but I'm having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.
I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?
As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.
json rest grails file-upload
add a comment |
This is probably going to be a stupid question but I'm having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.
I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?
As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.
json rest grails file-upload
So, what's the best way to do this?
– James111
Dec 15 '15 at 9:29
Send the metadata in the URL query string, instead of JSON.
– jrc
Aug 8 '17 at 15:49
add a comment |
This is probably going to be a stupid question but I'm having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.
I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?
As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.
json rest grails file-upload
This is probably going to be a stupid question but I'm having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.
I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?
As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.
json rest grails file-upload
json rest grails file-upload
edited Jan 19 '17 at 14:14
Dhruvan Ganesh
1,06111223
1,06111223
asked Nov 3 '10 at 2:07
GreggGregg
20.9k982166
20.9k982166
So, what's the best way to do this?
– James111
Dec 15 '15 at 9:29
Send the metadata in the URL query string, instead of JSON.
– jrc
Aug 8 '17 at 15:49
add a comment |
So, what's the best way to do this?
– James111
Dec 15 '15 at 9:29
Send the metadata in the URL query string, instead of JSON.
– jrc
Aug 8 '17 at 15:49
So, what's the best way to do this?
– James111
Dec 15 '15 at 9:29
So, what's the best way to do this?
– James111
Dec 15 '15 at 9:29
Send the metadata in the URL query string, instead of JSON.
– jrc
Aug 8 '17 at 15:49
Send the metadata in the URL query string, instead of JSON.
– jrc
Aug 8 '17 at 15:49
add a comment |
11 Answers
11
active
oldest
votes
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
- Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
- Send the file first in a
multipart/form-data
POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata. - Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
21
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
11
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
12
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
6
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
7
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
|
show 9 more comments
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
1
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
13
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
3
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
2
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
4
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
add a comment |
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related
request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
"name": "Sample image",
"desc": "...",
...
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
add a comment |
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save())
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
else
println("Error")
I don't know if I have problems in future, but now is working fine in production environment.
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
add a comment |
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identyicator in server) in API:
1.Create 'photo' object on server:
POST: /projects/project_id/photos
params in: name:some_schema.jpg, comment:blah
return: photo_id
2.Upload file (note that 'file' is in singular form because it is only one per photo):
POST: /projects/project_id/photos/photo_id/file
params in: file to upload
return: -
And then for instance:
3.Read photos list
GET: /projects/project_id/photos
params in: -
return: array of objects: [ photo, photo, photo, ... ]
4.Read some photo details
GET: /projects/project_id/photos/photo_id
params in: -
return: photo = id: 666, name:'some_schema.jpg', comment:'blah'
5.Read photo file
GET: /projects/project_id/photos/photo_id/file
params in: -
return: file content
So the conclusion is that, first you create object (photo) by POST, and then you send secod request with file (again POST).
2
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
1
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
|
show 9 more comments
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String>
@Override
protected void onPreExecute()
// set a status bar or show a dialog to the user here
super.onPreExecute();
@Override
protected void onProgressUpdate(Integer... progress)
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
@Override
protected String doInBackground(Void... params)
return uploadFile();
private String uploadFile()
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener()
@Override
public void transferred(long num)
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
);
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200)
responseString = EntityUtils.toString(httpEntity);
else
responseString = "Error, http status: "
+ statusCode;
catch (Exception e)
responseString = e.getMessage();
return responseString;
@Override
protected void onPostExecute(String result)
// if you want update the user interface with upload result
super.onPostExecute(result);
So, when you want to upload your file just call:
new UploadFile().execute();
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
1
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
add a comment |
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload()
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function ()
if (xhr.readyState == 4)
alert('success');
else if (uploadResult == 'success')
alert('error');
;
xhr.send(fd);
https://developer.mozilla.org/en-US/docs/Web/API/FormData
add a comment |
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, @RequestParam("uuid") String uuid,
@RequestParam("type") DocType type,
@RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
add a comment |
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr)
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
add a comment |
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token)
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld)
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
1
This getjava.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
add a comment |
If you are developing a rest server you can do this
- Have the client expose the file over HTTP
- The client can then send the url with your json data e.g an image file
"file_url":"http://cockwombles.com/blah.jpg"
- The server can then download the file.
3
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
add a comment |
protected by Josh Crozier Apr 25 '17 at 23:49
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
- Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
- Send the file first in a
multipart/form-data
POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata. - Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
21
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
11
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
12
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
6
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
7
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
|
show 9 more comments
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
- Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
- Send the file first in a
multipart/form-data
POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata. - Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
21
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
11
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
12
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
6
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
7
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
|
show 9 more comments
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
- Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
- Send the file first in a
multipart/form-data
POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata. - Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
- Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
- Send the file first in a
multipart/form-data
POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata. - Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
edited yesterday
Sergio B
156
156
answered Nov 3 '10 at 2:59
Daniel T.Daniel T.
18.7k29114181
18.7k29114181
21
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
11
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
12
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
6
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
7
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
|
show 9 more comments
21
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
11
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
12
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
6
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
7
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
21
21
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
If I chose option 1, do I just include the Base64 content inside the JSON string? file:'234JKFDS#$@#$MFDDMS....', name:'somename'... Or is there something more to it?
– Gregg
Nov 3 '10 at 3:06
11
11
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
Gregg, exactly as you've said, you would just include it as a property, and the value would be the base64-encoded string. This is probably the easiest method to go with, but might not be practical depending on the file size. For example, for our application, we need to send iPhone images that are 2-3 MB each. An increase of 33% is not acceptable. If you're sending only small 20KB images, that overhead might be more acceptable.
– Daniel T.
Nov 3 '10 at 3:14
12
12
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
I should also mention that the base64 encoding/decoding will also take some processing time. It might be the easiest thing to do, but it's certainly not the best.
– Daniel T.
Nov 3 '10 at 3:25
6
6
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
json with base64? hmm.. I'm thinking about sticking to multipart/form
– Omnipresent
May 16 '13 at 0:12
7
7
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
Why it is deny to use multipart/form-data in one request?
– 1nstinct
Jul 16 '15 at 6:34
|
show 9 more comments
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
1
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
13
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
3
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
2
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
4
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
add a comment |
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
1
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
13
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
3
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
2
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
4
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
add a comment |
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
answered Nov 3 '10 at 2:49
McStretchMcStretch
18.2k12839
18.2k12839
1
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
13
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
3
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
2
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
4
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
add a comment |
1
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
13
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
3
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
2
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
4
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
1
1
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
Thanks, but my question was focused on wanting to use JSON for the request and if that was possible. I already know that I could send it the way you suggest.
– Gregg
Nov 3 '10 at 3:05
13
13
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
Yeah that's essentially my response for "Should I not be using JSON for this?" Is there a specific reason why you want the client to use JSON?
– McStretch
Nov 3 '10 at 3:10
3
3
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
Most likely a business requirement or keeping with consistency. Of course, the ideal thing to do is accept both (form data and JSON response) based on the Content-Type HTTP header.
– Daniel T.
Nov 3 '10 at 3:17
2
2
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
Choosing JSON results much more elegant code in both client and server side, which leads to less potential bugs. Form data is so yesterday.
– superarts.org
May 14 '15 at 3:57
4
4
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
I apologize for what I said if it hurt some .Net developer's feeling. Although English is not my native language, it's not a valid excuse for me to say something rude about the technology itself. Using form data is awesome and if you keep using it you'll be even more awesome, too!
– superarts.org
Jun 10 '16 at 1:02
add a comment |
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related
request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
"name": "Sample image",
"desc": "...",
...
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
add a comment |
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related
request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
"name": "Sample image",
"desc": "...",
...
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
add a comment |
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related
request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
"name": "Sample image",
"desc": "...",
...
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related
request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
"name": "Sample image",
"desc": "...",
...
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
answered May 23 '16 at 15:03
pgiecekpgiecek
5,23212137
5,23212137
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
add a comment |
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
I liked your solution the best by far. Unfortunately, there appears to be no way to create mutlipart/related requests in a browser.
– Petr Baudis
May 27 '16 at 22:12
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
Would it not be possible to just build up the body manually?
– pip
Aug 12 '16 at 9:32
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
do you have any experience in getting clients to (especially JS ones) to communicate with the api in this way
– pvgoddijn
Sep 29 '16 at 11:07
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
unfortunately, there's currently no reader for this kind of data on php (7.2.1) and you would have to build your own parser
– dewd
Jul 24 '18 at 13:49
add a comment |
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save())
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
else
println("Error")
I don't know if I have problems in future, but now is working fine in production environment.
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
add a comment |
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save())
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
else
println("Error")
I don't know if I have problems in future, but now is working fine in production environment.
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
add a comment |
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save())
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
else
println("Error")
I don't know if I have problems in future, but now is working fine in production environment.
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save())
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
else
println("Error")
I don't know if I have problems in future, but now is working fine in production environment.
edited Aug 28 '13 at 13:38
Nikhil Agrawal
17.2k1673109
17.2k1673109
answered Jan 31 '12 at 17:49
RscorreiaRscorreia
14113
14113
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
add a comment |
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
I like this option of using http headers. This works especially well when there is some symmetry between the metadata and standard http headers, but you can obviously invent your own.
– EJ Campbell
Jan 8 '14 at 3:37
add a comment |
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identyicator in server) in API:
1.Create 'photo' object on server:
POST: /projects/project_id/photos
params in: name:some_schema.jpg, comment:blah
return: photo_id
2.Upload file (note that 'file' is in singular form because it is only one per photo):
POST: /projects/project_id/photos/photo_id/file
params in: file to upload
return: -
And then for instance:
3.Read photos list
GET: /projects/project_id/photos
params in: -
return: array of objects: [ photo, photo, photo, ... ]
4.Read some photo details
GET: /projects/project_id/photos/photo_id
params in: -
return: photo = id: 666, name:'some_schema.jpg', comment:'blah'
5.Read photo file
GET: /projects/project_id/photos/photo_id/file
params in: -
return: file content
So the conclusion is that, first you create object (photo) by POST, and then you send secod request with file (again POST).
2
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
1
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
|
show 9 more comments
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identyicator in server) in API:
1.Create 'photo' object on server:
POST: /projects/project_id/photos
params in: name:some_schema.jpg, comment:blah
return: photo_id
2.Upload file (note that 'file' is in singular form because it is only one per photo):
POST: /projects/project_id/photos/photo_id/file
params in: file to upload
return: -
And then for instance:
3.Read photos list
GET: /projects/project_id/photos
params in: -
return: array of objects: [ photo, photo, photo, ... ]
4.Read some photo details
GET: /projects/project_id/photos/photo_id
params in: -
return: photo = id: 666, name:'some_schema.jpg', comment:'blah'
5.Read photo file
GET: /projects/project_id/photos/photo_id/file
params in: -
return: file content
So the conclusion is that, first you create object (photo) by POST, and then you send secod request with file (again POST).
2
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
1
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
|
show 9 more comments
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identyicator in server) in API:
1.Create 'photo' object on server:
POST: /projects/project_id/photos
params in: name:some_schema.jpg, comment:blah
return: photo_id
2.Upload file (note that 'file' is in singular form because it is only one per photo):
POST: /projects/project_id/photos/photo_id/file
params in: file to upload
return: -
And then for instance:
3.Read photos list
GET: /projects/project_id/photos
params in: -
return: array of objects: [ photo, photo, photo, ... ]
4.Read some photo details
GET: /projects/project_id/photos/photo_id
params in: -
return: photo = id: 666, name:'some_schema.jpg', comment:'blah'
5.Read photo file
GET: /projects/project_id/photos/photo_id/file
params in: -
return: file content
So the conclusion is that, first you create object (photo) by POST, and then you send secod request with file (again POST).
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identyicator in server) in API:
1.Create 'photo' object on server:
POST: /projects/project_id/photos
params in: name:some_schema.jpg, comment:blah
return: photo_id
2.Upload file (note that 'file' is in singular form because it is only one per photo):
POST: /projects/project_id/photos/photo_id/file
params in: file to upload
return: -
And then for instance:
3.Read photos list
GET: /projects/project_id/photos
params in: -
return: array of objects: [ photo, photo, photo, ... ]
4.Read some photo details
GET: /projects/project_id/photos/photo_id
params in: -
return: photo = id: 666, name:'some_schema.jpg', comment:'blah'
5.Read photo file
GET: /projects/project_id/photos/photo_id/file
params in: -
return: file content
So the conclusion is that, first you create object (photo) by POST, and then you send secod request with file (again POST).
edited Jan 5 '17 at 15:20
answered Jul 10 '16 at 20:31
Kamil KiełczewskiKamil Kiełczewski
12.5k86896
12.5k86896
2
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
1
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
|
show 9 more comments
2
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
1
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
2
2
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
This seems like the more 'RESTFUL' way to achieve this.
– James Webster
Oct 17 '16 at 5:10
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
POST operation for newly created resources, must return location id, in simple version details of the object
– ivan.proskuryakov
Jan 4 '17 at 15:52
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
@ivanproskuryakov why "must"? In the example above (POST in point 2) the file id is useless. Second argument (for POST in point 2) i use singular form '/file' (not '/files') so ID is not needed because path: /projects/2/photos/3/file give FULL information to identity photo file.
– Kamil Kiełczewski
Jan 4 '17 at 16:27
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
From HTTP protocol specification. w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.2.2 201 Created "The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field." @KamilKiełczewski (one) and (two) could be combined into one POST operation POST: /projects/project_id/photos Will return you location header, which could be used for GET single photo(resource*) operation GET: to get a single photo with all details CGET: to get all collection of the photos
– ivan.proskuryakov
Jan 5 '17 at 9:06
1
1
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
If metadata and upload are separate operations, then the endpoints have these issues: For file upload POST operation used - POST is not idempotent. PUT(idempotent) must be used since you are changing the resource without creating a new one. REST works with objects called resources. POST: “../photos/“ PUT: “../photos/photo_id” GET: “../photos/“ GET: “../photos/photo_id” PS. Separating upload into separate endpoint may lead to unpredicted behavior. restapitutorial.com/lessons/idempotency.html restful-api-design.readthedocs.io/en/latest/resources.html
– ivan.proskuryakov
Jan 8 '17 at 10:21
|
show 9 more comments
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String>
@Override
protected void onPreExecute()
// set a status bar or show a dialog to the user here
super.onPreExecute();
@Override
protected void onProgressUpdate(Integer... progress)
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
@Override
protected String doInBackground(Void... params)
return uploadFile();
private String uploadFile()
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener()
@Override
public void transferred(long num)
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
);
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200)
responseString = EntityUtils.toString(httpEntity);
else
responseString = "Error, http status: "
+ statusCode;
catch (Exception e)
responseString = e.getMessage();
return responseString;
@Override
protected void onPostExecute(String result)
// if you want update the user interface with upload result
super.onPostExecute(result);
So, when you want to upload your file just call:
new UploadFile().execute();
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
1
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
add a comment |
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String>
@Override
protected void onPreExecute()
// set a status bar or show a dialog to the user here
super.onPreExecute();
@Override
protected void onProgressUpdate(Integer... progress)
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
@Override
protected String doInBackground(Void... params)
return uploadFile();
private String uploadFile()
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener()
@Override
public void transferred(long num)
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
);
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200)
responseString = EntityUtils.toString(httpEntity);
else
responseString = "Error, http status: "
+ statusCode;
catch (Exception e)
responseString = e.getMessage();
return responseString;
@Override
protected void onPostExecute(String result)
// if you want update the user interface with upload result
super.onPostExecute(result);
So, when you want to upload your file just call:
new UploadFile().execute();
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
1
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
add a comment |
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String>
@Override
protected void onPreExecute()
// set a status bar or show a dialog to the user here
super.onPreExecute();
@Override
protected void onProgressUpdate(Integer... progress)
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
@Override
protected String doInBackground(Void... params)
return uploadFile();
private String uploadFile()
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener()
@Override
public void transferred(long num)
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
);
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200)
responseString = EntityUtils.toString(httpEntity);
else
responseString = "Error, http status: "
+ statusCode;
catch (Exception e)
responseString = e.getMessage();
return responseString;
@Override
protected void onPostExecute(String result)
// if you want update the user interface with upload result
super.onPostExecute(result);
So, when you want to upload your file just call:
new UploadFile().execute();
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String>
@Override
protected void onPreExecute()
// set a status bar or show a dialog to the user here
super.onPreExecute();
@Override
protected void onProgressUpdate(Integer... progress)
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
@Override
protected String doInBackground(Void... params)
return uploadFile();
private String uploadFile()
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener()
@Override
public void transferred(long num)
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
);
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200)
responseString = EntityUtils.toString(httpEntity);
else
responseString = "Error, http status: "
+ statusCode;
catch (Exception e)
responseString = e.getMessage();
return responseString;
@Override
protected void onPostExecute(String result)
// if you want update the user interface with upload result
super.onPostExecute(result);
So, when you want to upload your file just call:
new UploadFile().execute();
edited Jan 10 '18 at 9:45
answered Sep 13 '15 at 9:40
lifeisfoolifeisfoo
6,74624368
6,74624368
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
1
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
add a comment |
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
1
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
Hi, what is AndroidMultiPartEntity please explain... and if i want to upload pdf, word or xls file what i have to do, please give some guidance... i am new to this.
– amit pandya
Jan 9 '18 at 11:09
1
1
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
@amitpandya I've changed the code to a generic file upload so it's more clear to anyone reading it
– lifeisfoo
Jan 10 '18 at 9:46
add a comment |
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload()
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function ()
if (xhr.readyState == 4)
alert('success');
else if (uploadResult == 'success')
alert('error');
;
xhr.send(fd);
https://developer.mozilla.org/en-US/docs/Web/API/FormData
add a comment |
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload()
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function ()
if (xhr.readyState == 4)
alert('success');
else if (uploadResult == 'success')
alert('error');
;
xhr.send(fd);
https://developer.mozilla.org/en-US/docs/Web/API/FormData
add a comment |
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload()
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function ()
if (xhr.readyState == 4)
alert('success');
else if (uploadResult == 'success')
alert('error');
;
xhr.send(fd);
https://developer.mozilla.org/en-US/docs/Web/API/FormData
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload()
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function ()
if (xhr.readyState == 4)
alert('success');
else if (uploadResult == 'success')
alert('error');
;
xhr.send(fd);
https://developer.mozilla.org/en-US/docs/Web/API/FormData
edited Jun 17 '15 at 13:29
Ikar Pohorský
1,34511333
1,34511333
answered Jul 4 '14 at 9:07
lakhan_Ideavatelakhan_Ideavate
165110
165110
add a comment |
add a comment |
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, @RequestParam("uuid") String uuid,
@RequestParam("type") DocType type,
@RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
add a comment |
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, @RequestParam("uuid") String uuid,
@RequestParam("type") DocType type,
@RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
add a comment |
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, @RequestParam("uuid") String uuid,
@RequestParam("type") DocType type,
@RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, @RequestParam("uuid") String uuid,
@RequestParam("type") DocType type,
@RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
edited Sep 18 '18 at 18:22
answered Sep 1 '18 at 14:08
Aslam anwerAslam anwer
510614
510614
add a comment |
add a comment |
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr)
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
add a comment |
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr)
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
add a comment |
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr)
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr)
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
answered Mar 30 '15 at 9:47
sunleosunleo
4,3732375135
4,3732375135
add a comment |
add a comment |
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token)
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld)
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
1
This getjava.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
add a comment |
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token)
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld)
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
1
This getjava.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
add a comment |
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token)
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld)
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token)
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld)
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
answered Oct 10 '15 at 14:54
Mak KulMak Kul
351
351
1
This getjava.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
add a comment |
1
This getjava.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
1
1
This get
java.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
This get
java.lang.ClassCastException: org.springframework.core.io.FileSystemResource cannot be cast to java.lang.String
– Mariano Ruiz
Dec 28 '15 at 21:04
add a comment |
If you are developing a rest server you can do this
- Have the client expose the file over HTTP
- The client can then send the url with your json data e.g an image file
"file_url":"http://cockwombles.com/blah.jpg"
- The server can then download the file.
3
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
add a comment |
If you are developing a rest server you can do this
- Have the client expose the file over HTTP
- The client can then send the url with your json data e.g an image file
"file_url":"http://cockwombles.com/blah.jpg"
- The server can then download the file.
3
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
add a comment |
If you are developing a rest server you can do this
- Have the client expose the file over HTTP
- The client can then send the url with your json data e.g an image file
"file_url":"http://cockwombles.com/blah.jpg"
- The server can then download the file.
If you are developing a rest server you can do this
- Have the client expose the file over HTTP
- The client can then send the url with your json data e.g an image file
"file_url":"http://cockwombles.com/blah.jpg"
- The server can then download the file.
answered Mar 17 '17 at 14:20
jim smithjim smith
93651729
93651729
3
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
add a comment |
3
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
3
3
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
This is not ideal as (a) the client has to run an http server, (b) there is no guarantee the server can connect back to the client (firewall issues)
– davidfrancis
Sep 20 '17 at 9:10
add a comment |
protected by Josh Crozier Apr 25 '17 at 23:49
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
So, what's the best way to do this?
– James111
Dec 15 '15 at 9:29
Send the metadata in the URL query string, instead of JSON.
– jrc
Aug 8 '17 at 15:49