我嘗試從前端發送一個包含 BLOB 變量的 Json 對象:
imageToBlob(file).then(result =>{
const imageData={blobData: result} //JSON DATA
axios.post('http://localhost:8080/saveImage', imageData)
.then();
})
當我記錄結果時,瀏覽器會打印:
Blob {size: 67386, type: 'image/png'}
size: 67386
type: "image/png"
[[Prototype]]: Blob
當我嘗試將其保存到 MySQL 數據庫時,我在 Spring 中收到此錯誤:
[nio-8080-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `[B` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `[B` from Object value (token `JsonToken.START_OBJECT`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 13] (through reference chain: com.example.pictureprojecttestbackend.entity.Picture["blobData"])]
實體:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Picture {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
@Lob
byte[] blobData;
}
發布請求:
@RestController
public class PictureController {
@Autowired
PictureRepository pictureRepository;
@PostMapping(value = "/saveImage", consumes = "application/json")
public void addImage(@RequestBody Picture picture){
pictureRepository.save(picture);
}
}
我究竟做錯了什麼?我發送了錯誤的 Json 結構還是關於實體的問題?
文件是通常無法輕易轉換為 JSON 的字節數組。這是您嘗試執行的操作,但在此轉換過程中失敗。
你最好用content-type "multipart/form-data"
嘗試以下
@Lob
@Type(type = "org.hibernate.type.ImageType")
byte[] blobData;
然後
@PostMapping(value = "/saveImage")
public void addImage(@RequestParam("file") MultipartFile file){
Picture picture = new Picture();
picture.setBlobData(file.getBytes());
pictureRepository.save(picture);
}
然後調整你的前端
imageToBlob(file).then(result =>{
var file = result;
var formData = new FormData();
formData.append("file", file);
axios.post('http://localhost:8080/saveImage', formData,
{ headers: { 'Content-Type': 'multipart/form-data' } });
.then();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句