Bre*_*min 6 rest multipartform-data spring-mvc spring-boot postman
我想通过邮递员将图像上传到我的Rest API.我正在使用spring boot框架.这是屏幕截图:
我也没有像我在其他堆栈溢出答案中找到的那样设置任何头文件,因为它给出了多部分边界错误.
现在,下面是我的控制器代码:
package com.practice.rest.assignment1.controller;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.practice.rest.assignment1.model.Product;
import com.practice.rest.assignment1.service.CatalogueService;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
@RestController
@RequestMapping("/CatalogueController/")
public class CatalogueController{
@Autowired
private CatalogueService catalogueService;
@RequestMapping(value = "addProduct", method = RequestMethod.POST , consumes = "multipart/form-data")
public Product addProduct(@RequestParam String productJson, @RequestParam MultipartFile file) throws JsonParseException, JsonMappingException, IOException {
Product product = new ObjectMapper().readValue(productJson, Product.class);
byte[] mediaBytes = file.getBytes();
product.setImage(mediaBytes);
return catalogueService.saveInDb(product);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我正在使用一个Product对象,该对象内部包含一个定义为byte []数组的图像.我把它作为字符串和图像分别作为Multipart文件.
以下是我定义的产品类属性:
private Long pId;
private String model;
private String brand;
private byte[] image; // This is where I want the image to save
private Long price;
private String currency;
private String transmissionType;
private String fuelType;
Run Code Online (Sandbox Code Playgroud)
既然,我正在使用spring boot,这是我的Main类:
package com.practice.rest.assignment1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的邮差错误是:
{
"timestamp": 1478611635977,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.multipart.support.MissingServletRequestPartException",
"message": "Required request part 'file' is not present",
"path": "/CatalogueController/addProduct"
}
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
我认为问题出在您发送的 JSON 参数上。在邮递员中,您不需要放置开头和结尾的“来将参数表示为字符串。而且,如果您使用开头和结尾“,那么在JSON(对于JSON对象意味着属性键和值)中,您应该使用'(单引号)。
归档时间: |
|
查看次数: |
24937 次 |
最近记录: |