一次上傳多張圖片,用 ASIFormDataRequest 就能寫得很簡潔。關鍵在於以 multipart/form-data 格式提交,並把每張圖片各自作為一個檔案部件加入。
NSURL *url = [NSURL URLWithString:@"ios 開發教程 www.51ios.net"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.uploadProgressDelegate = viewPost.progressView; // 綁定進度條
request.showAccurateProgress = YES; // 顯示精確進度
request.shouldContinueWhenAppEntersBackground = YES; // 進入背景後繼續上傳
if ([imageArray count] > 0) {
[request setPostFormat:ASIMultipartFormDataPostFormat];
for (NSData *data in imageArray) {
NSInteger idx = [imageArray indexOfObject:data];
[request addData:data
withFileName:[NSString stringWithFormat:@"image%d.png", idx]
andContentType:@"image/png"
forKey:@"photos[]"];
}
}
1. 每張圖取不同檔名:範例用 idx 作為檔名的一部分,避免同名覆蓋。若後端依檔名去重,這一步是必要的。
2. contentType 要對得上實際格式:範例寫死 image/png,但 imageArray 裡的資料若實際是 JPEG,就必須改成 image/jpeg,否則部分後端會拒收或存成打不開的檔案。
3. 記得設定 delegate 與啟動 request:這段程式只完成「組裝」,還需要 [request startAsynchronous] 或 startSynchronous,並在 response 回來後處理伺服器回應。
4. ASIHTTPRequest 已停止維護:新專案建議改用 AFNetworking 的 AFHTTPSessionManager multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:,或原生的 URLSession。寫法更簡潔,也支援背景上傳任務。