我需要給第三方api發圖片,但是出現錯誤 {"timestamp": "2021-11-15T15: 25: 06.532 00: 00", "status": 500, "error": "Internal服務器錯誤", "路徑":"/api/send/"}
如果我直接聯系服務(郵遞員 http://exampleResourese/sendimg),那么我正常得到答案,那么問題出在我的代碼中(在端點 http://localhost:8091/api/send 上)。
告訴我如何通過 RestTemplate 或其他方法發送圖片。
第三方服務接受圖片字串($binary)
控制器:
@RequestMapping(value = "/send",method = RequestMethod.POST)
public ResponseEntity<?> sendCopyPassport(@RequestParam("images") MultipartFile files) throws MalformedURLException, IOException{
return documentsReceivingService.uploadAndGetListDocuments(files);
}
服務 :
@Service 公共類 DocumentsReceivingService {
@Autowired
RestTemplate restTemplate;
private final String UPLOADFILE = "http://exampleResourese/sendimg";
Logger logger = LoggerFactory.getLogger(DocumentsReceivingService.class);
public ResponseEntity<?> uploadAndGetListDocuments(MultipartFile files) throws MalformedURLException, IOException{
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
Charset charset = Charset.forName("UTF-8");
String str =null;
byte[] bytes =null;
try{
bytes = files.getBytes();
str = new String(bytes,charset);
} catch (IOException e) {
ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body( new MessageResponse("err"));
}
map.add("images",str);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
String response = restTemplate.postForEntity(UPLOADFILE, requestEntity, String.class);
return ResponseEntity.ok(response);
}
錯誤:
Response 500 INTERNAL_SERVER_ERROR
2021-11-15 20:43:00.938 DEBUG 22308 --- [nio-8091-exec-2] o.s.web.servlet.DispatcherServlet : Failed to complete request: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: "{"error": "Serious unexpected error"}"
2021-11-15 20:43:00.938 ERROR 22308 --- [nio-8091-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: "{"error": "Serious unexpected error"}"] with root cause
org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: "{"error": "Serious unexpected error"}"
請告訴我如何正確傳輸圖片?這張圖片會從前端加載,然后到我的服務器,然后我將它進一步傳輸到端點
uj5u.com熱心網友回復:
如果您使用該服務作為代理(并且您不打算將檔案下載到您的導演),則嘗試通過請求 json 到 base64(將位元組編碼為 base64)來傳輸檔案。例如 :
{
"file": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA .. "
}
檢查第三方服務將接受的形式。
盡管如此,如果您想使用 multipart,請將其保存在目錄中的某個位置,然后從那里將檔案上傳到另一個服務(因為您說如果您使用郵遞員,它會正常發送它,并從您的 PC 發送它目錄),在這種情況下 File 類會有所幫助。測驗,如果有問題,則顯示執行結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/362663.html
