개발/Dart & Flutter

[Flutter] dio로 이미지 여러 장 전송하기 - Send multiple images on multipart/form-data

Monsh 2022. 2. 8. 12:16
반응형

Flutter 공식 http 라이브러리에는 귀찮은 점이 하나 있다.

 

application/x-www-form-urlencoded 타입의 post request는 별로 문제가 안 되는데,

multipart/form-data 타입은 꽤 번거롭다는 것이다.

 

그래서, 고집 부리지 않고 그냥 dio를 사용하기로 했다.


Dio

기본 http 라이브러리보다 편하다.
Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.를 제공한다.


하나의 파일을 multipart/form-data 타입으로 post request

var ido = Dio();

var formData = FormData.fromMap({
  'name': '문자열',
  'age': int,
  'file': await MultipartFile.fromFile(filepath, filename: '이름.확장자')
});

response = await dio.post('타겟 url', data: formData);

(filepath는 문자열이다.)
파일 하나는 이렇게 보내면 되는데, 복수의 파일은 주의가 필요하다.


여러 파일을 multipart/form-data 타입으로 post request

var ido = Dio();

var formData = FormData.fromMap({
  'name': '문자열',
  'age': int,
  'files[]': [
    MultipartFile.fromFileSync(filepath, filename: '이름.확장자'),
    MultipartFile.fromFileSync(filepath, filename: '이름.확장자'),
  ]
});

response = await dio.post('타겟 url', data: formData);

dio 홈페이지에서는 다음과 같이 설명하고 있다.

The upload key eventually becomes 'files[]'
This is because many back-end services add a middle bracket to key when they get an array of files. 
If you don't want “[]”,you should create FormData as follows
(Don't use FormData.fromMap)

becomes라고 해서 키값 끝에 자동으로 []가 붙는 줄 알았는데

파일 리스트를 보내고 싶을 경우 우리가 붙여야 한다.

 

사실, 이것은 Vue.js에서 FormData를 쏠 때도 마찬가지였다.

HTTP request 같은 건 보통, 만들어 놓고 잘 동작하면 다시 볼 일이 적으니
그냥 내가 잊었던 것이다.


PDO에서 multipart/form-data request를 받아서 쓰기

$files = $_FILES['files'];

$files['tmp_name'][$index]; // 캐시 저장소의 파일 경로
$files['name'][$index]; // 파일 이름

사용할 때는,

배열[인덱스][키]가 아니라 배열[키][인덱스]라는 것도 기억하자.

(왜 그런지는, JSON으로 변환해서 구조를 확인해보면 알 수 있다.)

반응형