我构建了一个由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时,我收到错误&#34;客户端发送的请求在语法上是不正确的。&#34;。这是我的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以将多个图像上传到服务器? 感谢
答案 0 :(得分:3)
为什么标准方式,对你不起作用? 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
Using curl to upload POST data with files
如果您需要更多元数据,可以将Cookie添加到上传控制器
@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