java Multipart/form-data Restful 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43729185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multipart/form-data Restful request
提问by phalco
I am working with multipart/form-data POST request which is divided by boundaries.
我正在处理按边界划分的 multipart/form-data POST 请求。
POST .... HTTP/1.1
.
.
.
---boundary123
Content-type:application/octet-stream
content-Disposition: form-data filenale="payload.txt" name="someuniquename"
[paylaod content](this is in xml format)
---boundary123
content-type:application/json
content-Disposition:form-data name="someuniquname"
{ID:"999"}
---boundary123
How can I handle this multipart request? I also want to validate the data before making POST request by using Spring4 and REST.
我该如何处理这个多部分请求?我还想在使用 Spring4 和 REST 发出 POST 请求之前验证数据。
采纳答案by user1849477
you should follow the below code :
您应该遵循以下代码:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@RequestMapping(value="/singleUpload")
public String singleUpload(){
return "singleUpload";
}
@RequestMapping(value="/singleSave", method=RequestMethod.POST )
public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file, @RequestParam("desc") String desc ){
System.out.println("File Description:"+desc);
String fileName = null;
if (!file.isEmpty()) {
try {
fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));
buffStream.write(bytes);
buffStream.close();
return "You have successfully uploaded " + fileName;
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage();
}
} else {
return "Unable to upload. File is empty.";
}
}
@RequestMapping(value="/multipleUpload")
public String multiUpload(){
return "multipleUpload";
}
@RequestMapping(value="/multipleSave", method=RequestMethod.POST )
public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){
String fileName = null;
String msg = "";
if (files != null && files.length >0) {
for(int i =0 ;i< files.length; i++){
try {
fileName = files[i].getOriginalFilename();
byte[] bytes = files[i].getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));
buffStream.write(bytes);
buffStream.close();
msg += "You have successfully uploaded " + fileName +"<br/>";
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage() +"<br/>";
}
}
return msg;
} else {
return "Unable to upload. File is empty.";
}
}
}
回答by phalco
This is how I handled the Multipart Request using Spring 4 (This is the the case when you don't know about filenames or total no. of files in Multipart Request)
这就是我使用 Spring 4 处理多部分请求的方式(当您不知道多部分请求中的文件名或文件总数时就是这种情况)
import org.springframework.web.multipart.MultipartHttpServletRequest;
@RequestMapping(value = "/your_webservice_path", method = RequestMethod.POST, consumes = "multipart/form-data")
public Void myController( MultipartHttpServletRequest request) throws Exception
{
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext()) {
String str=iterator.next().toString();
try{
//extract the file from request
}
catch(Exception ex){
logger.error("Error while parsing the Payload ro metadata from request", ex);
}
}
}
In Jersey2:
在泽西2:
import org.glassfish.jersey.media.multipart.MultiPart;
@POST
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Path("/your_webservice_path")
public void myController(MultiPart request) throws Exception {
//use request .getBodyParts() for extracting files from Multipart request
}
回答by Furquan Ahmed
@RequestMapping(value = "/upload",
method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String upload(
@RequestParam("file") final MultipartFile file,
@RequestParam("name") final String name) {
// your work here using the file. you can use file.getBytes()
// or get an input stream from file using file.getInputStream()
// and save it.
return "{\"status\" : \"success\"}";
}
You will get the file being uploaded in file argument and the String parameter name in your name argument.
您将在 file 参数中获取正在上传的文件,并在 name 参数中获取 String 参数名称。