我使用post方法上傳圖像,但每次發現以下錯誤: 操作無法完成。 (NSURLErrorDomain錯誤-1012)。上傳文件時出錯
請建議我用,我可以解決這個問題:(
NSString *urlString = [NSString stringWithFormat:@"%@%@",Base_URL,URL_Upload];
NSURL* requestURL = [NSURL URLWithString:urlString];
NSString *filename = imageName;
//creating request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
// set URL
[request setURL:requestURL];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
// post body
NSMutableData *postbody = [NSMutableData data];
NSData* imageData = UIImageJPEGRepresentation(image, 1);
if (imageData) {
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString* fileData = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", filename];
NSLog(@"fileData %@",fileData);
[postbody appendData:[fileData dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:imageData];
[postbody appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:postbody];
// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [postbody length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_connection start];
if (_connection) {
_reposnseData = [NSMutableData data];
}
嘗試使用[AFNetworking]的方式(https://github.com/AFNetworking/AFNetworking) –