Programing

우편 배달부에서 파일 및 json 데이터를 업로드하는 방법

lottogame 2020. 10. 18. 08:18
반응형

우편 배달부에서 파일 및 json 데이터를 업로드하는 방법


나는 Spring MVC를 사용하고 있으며 이것이 내 방법입니다.

/** 
* Upload single file using Spring Controller 
*/ 
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) 
public @ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) { 
    if (!file.isEmpty()) { 
        try { 
            byte[] bytes = file.getBytes();     
            // Creating the directory to store file 
            String rootPath = System.getProperty("catalina.home"); 
            File dir = new File(rootPath + File.separator + "tmpFiles"); 
            if (!dir.exists()) 
                dir.mkdirs();     
            // Create the file on server 
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name); 
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); 
            stream.write(bytes);
            stream.close(); 
            System.out.println("Server File Location=" + serverFile.getAbsolutePath());
            return null; 
        } catch (Exception e) { 
            return null; 
        } 
    } 
} 

우편 배달부와 파일에 세션 ID를 전달해야합니다. 어떻게 할 수 있습니까?


우편 배달부에서 메소드 유형을 POST로 설정하십시오 .

그런 다음 본문-> 양식 데이터-> 매개 변수 이름 입력 ( 코드에 따른 파일 )을 선택하십시오.

값 열 옆의 오른쪽에 "text, file"드롭 다운 이 표시되고 File을 선택 합니다. 이미지 파일을 선택하고 게시하십시오.

나머지 "텍스트"기반 매개 변수의 경우 우편 배달부에서 평소처럼 게시 할 수 있습니다. 매개 변수 이름을 입력하고 오른쪽 드롭 다운 메뉴에서 "텍스트"를 선택하고 값을 입력하고 보내기 버튼을 누르십시오. 컨트롤러 메서드가 호출되어야합니다.


아마도 다음과 같이 할 수 있습니다.

postman_file_upload_with_json


당신은해야한다 첫번째 의 거의 보이지 않는 옅은 회색에 흰색 드롭 다운 찾을 File마법의 키를 잠금 해제 그 어떤 Choose Files버튼을 누릅니다.

누락 된 비주얼 가이드 :

후에 당신이 선택 POST, 다음 선택 Body->form-data, 다음 파일 드롭 다운 메뉴를 찾은 다음 '파일'을 선택, 단지 다음 버튼 마술 표시 '파일 선택'을합니다 :

Postman POST 파일 설정-(텍스트, 파일) 드롭 다운 강조 표시


이렇게 :

여기에 이미지 설명 입력

본문-> 양식 데이터-> 파일 선택

"이름"대신 "파일"을 써야합니다.

또한 Body-> raw 필드에서 JSON 데이터를 보낼 수 있습니다. (JSON 문자열 붙여 넣기)


  1. 헤더를 제공하지 마십시오.
  2. json 데이터를 .json 파일에 넣으십시오.
  3. Select your both files one is your .txt file and other is .json file for your request param keys.

If somebody needed:

body -> form-data

Add field name as array

여기에 이미지 설명 입력


If you need like Upload file in multipart using form data and send json data(Dto object) in same POST Request

Get yor JSON object as String in Controller and make it Deserialize by adding this line

ContactDto contactDto  = new ObjectMapper().readValue(yourJSONString, ContactDto.class);

Postman 멀티 파트 양식 데이터 컨텐츠 유형

Select [Content Type] from [SHOW COLUMNS] then set content-type of "application/json" to the parameter of json text.


If somebody wants to send json data in form-data format just need to declare the variables like this

Postman:

As you see, the description parameter will be in basic json format, result of that:

{ description: { spanish: 'hola', english: 'hello' } }

I needed to pass both: a file and an integer. I did it this way:

  1. needed to pass a file to upload: did it as per Sumit's answer.

    Request type : POST

    Body -> form-data

    under the heading KEY, entered the name of the variable ('file' in my backend code).

    in the backend:

    file = request.files['file']

    Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.

2. needed to pass an integer:

went to:

Params

entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE

in the backend:

id = request.args.get('id')

Worked!


If you are using cookies to keep session, you can use interceptor to share cookies from browser to postman.

Also to upload a file you can use form-data tab under body tab on postman, In which you can provide data in key-value format and for each key you can select the type of value text/file. when you select file type option appeared to upload the file.


If you want to make a PUT request, just do everything as a POST request but add _method => PUT to your form-data parameters.


enter image description here

rest controller[service classapplicationinitializer class for multipart con[postman pic ]2fig

참고URL : https://stackoverflow.com/questions/39037049/how-to-upload-a-file-and-json-data-in-postman

반응형