티스토리 뷰

반응형

App Client에서 FileUpload 하는 방법은 multipart/form-data octet-stream으로 나눠집니다.

Alamofire 를 활용하여 multipart/form-data 파일 업로드를 구성하면 다음과 같이 구성할 것입니다.

/// 파일 업로드
/// - Parameters:
/// - data: 데이터 파일
/// - fName: 파일 이름
/// - contentType: contentType
/// - headers: headers
/// - complete: 완료 클로저
private func uploadData(data: Data?,fileName fName: String, contentType: String, headers:[String: String]?, complete: @escaping (_ response: UploadMap?)-> Void) {
guard let data = data else {
complete(nil)
return
}
let uploadUrl = "[업로드 도메인]"
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(data, withName: "file", fileName: fName, mimeType: contentType)
},
to: uploadUrl.url,
method: uploadUrl.method,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseObject { (response: DataResponse<UploadMap>) in
complete(response.result.value)
}
case .failure(let encodingError):
complete(nil)
}
}
)
}

 

업무를 하다보면 간혹 파일 업로드를 octet-stream으로 요구 할 때가 있습니다.

octet-stream 파일 업로드는 위의 multipart/form-data 와 동일한 방식으로 구성하되 header에 content-type을 application/octet-stream 을 추가로 선언하면 됩니다.

/// 파일 업로드
/// - Parameters:
/// - fileName: 파일 이름
/// - contentType: contentType
/// - fileData: 데이터 파일
/// - headers: headers
/// - complete: 완료 클로저
private func fileUpload(fileName:String?, contentType: String?, fileData: Data?, headers:[String: String]?, complete: @escaping (_ response: UploadMap?)-> Void) {
if let fileName = fileName, let contentType = contentType, let fileData = fileData {
if !fileName.isEmpty && !contentType.isEmpty && fileData.count > 0 {
let headers = [
"content-type" : "application/octet-stream"
] as HTTPHeaders
self.uploadData(data: fileData, file: fileName, contentType: contentType, headers: headers, complete: complete)
return
}
}
complete(nil)
}

 

마무리

 

간단히 파일 업로드 하는 방법에 대해서 알아봤습니다.

octet-stream , multipart/form-data 방식으로 파일 업로드 시 도움이 되면 좋겠습니다.

반응형
질문 또는 잘못된 정보는 댓글로 남겨주세요.

'프로그래밍 > iOS' 카테고리의 다른 글

[SWIFT] STOMP Client 맛보기  (2) 2020.04.18
iOS Shared Extention App Build Issue  (0) 2019.01.04
[SWIFT] 메일 보내는 방법 알아보자  (0) 2018.12.21
내부 배포용 앱 만들기(Enterprise)  (0) 2018.12.02
[SWIFT]클로저  (0) 2018.10.24
댓글