首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Multipart/form-data Restful请求

Multipart/form-data Restful请求
EN

Stack Overflow用户
提问于 2017-05-02 10:34:19
回答 3查看 17.7K关注 0票数 1

我正在处理由边界划分的multipart/form-data POST请求。

代码语言:javascript
复制
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

如何处理此多部分请求?我还想在使用Spring4和REST发出POST请求之前验证数据。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-05-02 10:55:47

您应该遵循以下代码:

代码语言:javascript
复制
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.";
        }
    }
} 
票数 1
EN

Stack Overflow用户

发布于 2017-05-02 10:53:19

代码语言:javascript
复制
@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\"}";
    }

您将在file参数中获取正在上载的文件,并在name参数中获取字符串参数名称。

票数 0
EN

Stack Overflow用户

发布于 2017-08-31 03:27:52

这就是我使用Spring4处理多部分请求的方式(这是当你不知道文件名或者完全不知道的时候。分块请求中的文件数量)

代码语言:javascript
复制
 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);
        }
    }
}

在Jersey2中:

代码语言:javascript
复制
 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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43729185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档