programing

우체부: 필수 요청 부품 'file'이(가) 없습니다.

instargram 2023. 7. 21. 20:34
반응형

우체부: 필수 요청 부품 'file'이(가) 없습니다.

저는 우체부를 통해 제 Rest API에 이미지를 업로드하고 싶었습니다.스프링 부츠 프레임워크를 사용하고 있습니다.스크린샷은 다음과 같습니다.

enter image description here

또한 다른 스택 오버플로 답변에서 다중 부분 경계 오류가 발생한다는 것을 발견했기 때문에 헤더를 설정하지 않았습니다.

다음은 제 컨트롤러 코드입니다.

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);

    }

}

이제 내부적으로 바이트[] 배열로 정의된 이미지로 구성된 Product 개체를 사용합니다.나는 이것을 문자열로, 이미지를 멀티파트 파일로 따로 가져갑니다.

다음은 정의된 제품 클래스 속성입니다.

    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;

봄부츠를 사용하고 있기 때문에, 나의 주요 수업은 다음과 같습니다.

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);  
  }

}

우체부가 받는 오류는 다음과 같습니다.

{
  "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"
}

어디가 틀렸습니까?

보내주신 JSON 파라미터에 문제가 있는 것 같습니다.우체부에서는 매개 변수를 문자열로 표시하기 위해 시작 및 후행 "을 입력할 필요가 없습니다.또한 "시작"과 "끝"을 사용한 다음 JSON 내부(JSON 개체의 평균 속성 키 및 값)에서 '(단일 따옴표)를 사용해야 합니다.

제거 시도'Content-Type: multipart/form-data...'머리글 섹션입니다.그것이 저를 위해 해결했습니다.

저는 application.properties에서 다음 변수를 설정했습니다.

spring.http.multipart.enabled=true 
spring.http.multipart.location= /upload

안녕 @Braking Benjamin 저도 같은 데모를 했고, 여기 제 포스트 요청 사본이 있습니다.

curl 'http://localhost:9999/api/v1/upload' -H 'Pragma: no-cache' \
-H 'Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' \
-H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary0ae4CymwYLjdqdI1' \
-H 'Accept: */*' -H 'Cache-Control: no-cache' \
-H 'Cookie: _ga=GA1.1.433565887.1474948752' \ 
-H 'Connection: keep-alive' -H 'DNT: 1' --data-binary $'------WebKitFormBoundary0ae4CymwYLjdqdI1\r\nContent-Disposition: form-data; name="file"; filename="228cb73.jpg"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary0ae4CymwYLjdqdI1\r\nContent-Disposition: form-data; name="a"\r\n\r\n123\r\n------WebKitFormBoundary0ae4CymwYLjdqdI1--\r\n' --compressed

업로드 컨트롤러는 다음과 같이 기록됩니다.

@RequestMapping(method = RequestMethod.POST)
    public ResponseEntity handleUpload(
            @RequestParam("a")String a,
            @RequestParam("file") MultipartFile multipartFile) throws IOException {

        System.out.println(a);
        ...

내 콘솔에서 파라미터는a가 성공적으로 출력:

param a output

json 문자열을 사용하여 요청을 다시 보내더라도:

curl 'http://localhost:9999/api/v1/upload' -H 'Pragma: no-cache' -H 'Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBTudL55M6S8ENLVt' -H 'Accept: */*' -H 'Cache-Control: no-cache' -H 'Cookie: _ga=GA1.1.433565887.1474948752' -H 'Connection: keep-alive' -H 'DNT: 1' --data-binary $'------WebKitFormBoundaryBTudL55M6S8ENLVt\r\nContent-Disposition: form-data; name="file"; filename="228cb73.jpg"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundaryBTudL55M6S8ENLVt\r\nContent-Disposition: form-data; name="a"\r\n\r\n"{"key":"value"}"\r\n------WebKitFormBoundaryBTudL55M6S8ENLVt--\r\n' --compressed

코드가 정상인 것 같습니다만, 사용해 보시겠습니까?curl요청을 다시 보내려면, 아마도 이것은 당신이 우체부를 잘못 사용했기 때문일 것입니다.

변수 worked spring.spring.spring.properties.enabled=true를 업데이트하여 application.properties를 업데이트하는 경우

나의 서비스는

@PostMapping(value = "/console")
public ResponseEntity<RxConsoleDTO> addRxConsole(@RequestParam("attachment") MultipartFile attachmentFile,  @RequestParam("type") String type) throws IOException {// your logic}

enter image description here

저도 같은 문제가 있었고 그것은 포스트맨 자체의 문제가 아닌 것으로 밝혀졌습니다.멀티파트 리졸버빈을 추가했더니 문제가 해결되었습니다.

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(-1);
    return multipartResolver;
}

또한 아래 속성이 활성화되어 있는지, 텍스트 파일을 업로드하는 경우 적절한 매개 변수로 간주되지 않는지 확인합니다.

upload.file.extensions=jpg, jpeg, gif, png

저도 같은 오류에 직면해서 당신의 질문에 부딪혔습니다.참고: API를 테스트하기 위해 pyTest를 작성하고 있었습니다.

나는 방금 파일에서 다음 행을 삭제했습니다.

'Content-Type': 'multipart/form-data; boundary=--------------------------561045520875406684819091',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',

그리고, 효과가 있었습니다 :)

언급URL : https://stackoverflow.com/questions/40488585/postman-required-request-part-file-is-not-present

반응형