繁体   English   中英

将正文请求POST中的多个文件上传到Spring Restful API

[英]Upload multiple files in body request POST to Spring Restful API

我正在通过Spring Restful构建一个上传多个图像的API。 这是我的API方法:

@RequestMapping(value = GiftURI.TEST_UPLOAD, method = RequestMethod.POST)
    public 
    @ResponseBody String testUploadMultipleFiles(@RequestBody TestUploadImageReq request) throws BusinessException {
        String fileName = "test";
        String filePath = "/Users/Dona/Desktop/";
        System.out.println("My name is " + request.getMyName());
        for (int i = 0; i < request.getImages().length; i++){
            if (!request.getImages()[i].isEmpty()) {
                try {
                    File newfile = new File(filePath+fileName+i+".jpg");
                    FileUtils.writeByteArrayToFile(newfile, request.getImages()[i].getBytes());
                } catch (Exception e) {
                    return "You failed to upload cause: " + e.toString();
                }
            }
        }
        return "Finished";
    }

这是我的TestUploadImageReq模型:

public class TestUploadImageReq implements Serializable  {
    private static final long serialVersionUID = 5284757625916162700L;
    public TestUploadImageReq(){}

    private MultipartFile[] images;
    private String myName;

    public String getMyName() {
        return myName;
    }

    public void setMyName(String myName) {
        this.myName = myName;
    }

    public MultipartFile[] getImages() {
        return images;
    }
    public void setImages(MultipartFile[] images) {
        this.images = images;
    }

}

但是,当我使用CURL命令测试此API时,收到错误消息“客户端发送的请求在语法上不正确。”。 这是我的CURL命令:

curl -i -X POST -H "Content-Type:application/json" http://localhost:9190/rest/gift/test_upload -d '{"myName":"Dona", "image":"@/Users/Dona/Desktop/mcdona2.jpg"}'

如何通过curl命令测试我的API,以将多个图像上传到服务器? 谢谢

为什么采用标准方式,对您不起作用? http://spring.io/guides/gs/uploading-files

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
...

而且您应该能够使用

curl -F "userid=1" -F "filecomment=This is an image file" -F "image=@/home/user1/Desktop/test.jpg" localhost:8080/upload

使用curl上传带有文件的POST数据

如果您需要更多元数据,则可以将Cookies添加到您的上传控制器中

@Controller
public class FileUploadWithMetaController {

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(
         @RequestParam("name") String name,
         @RequestParam("file") MultipartFile file,
         @CookieValue(value = "META", defaultValue = "no") String metaCookie){
...

CURL看起来像这样:

curl --cookie "META=Yes" -F "userid=1" -F "filecomment=This is an image file" -F "image=@/home/user1/Desktop/test.jpg" localhost:8080/upload

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM