我正在尝试使用spring rest和hibernate将json数据和图像上传到表单的数据库。我尝试使用POSTMAN测试它,通过将body和content-type中的form-data设置为header / json in header,但我得到http错误400.我也尝试使用@RequestPart
但是没有用。我搜索但找不到使用ResponseEnity<>
的示例。我想我在控制器类中做错了什么。请有人帮助我。
如果没有文件部分,我可以使用此功能将json数据添加到db。
@RequestMapping(value = "/users", method = RequestMethod.POST, produces ="application/json")
public ResponseEntity<User> createAparts( @RequestBody User user) {
if (user == null) {
return new ResponseEntity<User>(HttpStatus.BAD_REQUEST);
}
userService.addAparts(user);
return new ResponseEntity<User>(user, HttpStatus.CREATED);
}
以下是要发布的相关代码。
模型
@Entity
@Table(name = "User")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "ignoreUnknown = true"})
public class User{
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "Name")
private String Name;
@Column(name = "file_data")
private byte[] file_data;
@Column(name = "filename")
private String filename;
@JsonCreator
public ApartsData(@JsonProperty("id") int id,
@JsonProperty("Name") String Name,
@JsonProperty("filename") String filename,
@JsonProperty("file_data") byte[] file_data){
this.ad_id = ad_id;
this.Name = Name;
this.filename= filename;
this.file_data = file_data;
}
public User(){
}
DAO
@Repository
public class UserDaoImpl implements UserDao{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
@Override
public void addUser(User user) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
}
服务
@Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
@Transactional
public void addUser(User user) {
this.userDao.addUser(user);
}
}
控制器
@RestController
public class UserController {
private UserService userService;
@Autowired(required=true)
@Qualifier(value="userService")
public void setUserService(UserService userService){
this.userService = userService;
}
@RequestMapping(value = "/users", method = RequestMethod.POST,
produces ="application/json")
public ResponseEntity<User> createApartsData(@RequestBody User user,
@RequestParam("file") MultipartFile file) {
HttpHeaders headers = new HttpHeaders();
if (user == null) {
return new ResponseEntity<User>(HttpStatus.BAD_REQUEST);
}
if (!file.isEmpty()) {
try {
user.setFilename(file.getOriginalFilename());
user.setFile_data(file.getBytes());
} catch (Exception e){
e.printStackTrace();
}
}
userService.addUser(user);
headers.add("User Created - ", String.valueOf(user.getid()));
return new ResponseEntity<User>(user, headers, HttpStatus.CREATED);
}
}
更新
我能够使用@RequestParam
。请帮助我使用@RequestBody