REST: Using PUT to update with a file upload
I'm coding an API and got stuck on the UPDATE part of things. From what I've read about REST the update operation should be exposed by using HTTP PUT.
Ok, PUT gives me just a stream of data. At least in PHP the decoding of this data is my responsibility. So how do I mix string data and file upload and use P开发者_如何学JAVAUT? I know I can do it in POST but I'm trying to do it the RESTful way.
Should I use multipart/form-data and is that portable for PUT (I mean is it easy to send this kind of request in different languages)? I'm trying to figure out the proper
way to do this. Again, if I use multipart/form-data I'm responsible for the parsing so there might be some errors or performance degradation. Can you suggest a parser if this multipart/... is the way to do what I'm asking?
Thanks
General rule of PUT is that is idempotent
Calling 2x PUT /user/{userId}/files/foo.txt
ends up in the same state, with the 2nd call you would simply override the foo.txt. You are 'setting' things.
Calling 2x POST /user/{userId}/files
would end up in two different files. You are 'adding' things.
Therefore I would use PUT if you want to write to a dedicated target. What kind of files do you want to upload. E.g. if it is a picture-upload I would use POST (where you would get the target url inside response). If you are designing a kind of file-storage for a user I would use PUT, because most likely users want to write (set) to a certain location (like you would on a ordinary file-system).
Maybe you have more details/requirements for a concrete case?
What kind of data are you attempting to PUT
? Remember that PUT is a directed publishing method. The client sends data to the server and essentially says "PUT
this file into /home/sites/.../myfile.txt".
Useful for when you're publishing data to a site and are creating a new page. Not so useful if it's a standard file upload form ("Upload an avatar image here!"). You don't want to allow potentially malicious users to specify where an uploaded file should go.
That's when you use POST, which translates into "here's a file, it's called myfile.txt, do what you want with it".
精彩评论