如何将文件上传到服务器?

时间:2016-12-10 08:59:56

标签: ios objective-c iphone

我正在尝试将图片上传到服务器但总是从服务器收到错误。

  

标题。

     

内容类型:multipart / form-data;边界= ---边界

     

车身

     

-----边界

     

内容 - 处置:表单数据;命名="文件&#34 ;;文件名=" pic.jpg"

     

内容类型:image / jpeg

     

Content-Transfer-Encoding:base64

     

/ 9J / 4AAQSkZJRgABAQEAYABgAAD / 2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a   HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL / 2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy   MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL / wAARCAABAAEDASIA   AhEBAxEB / 8QAFQABAQAAAAAAAAAAAAAAAAAAAAf / xAAUEAEAAAAAAAAAAAAAAAAAAAAA / 8QAFAEB   AAAAAAAAAAAAAAAAAAAAAP / EABQRAQAAAAAAAAAAAAAAAAAAAAD / 2gAMAwEAAhEDEQA / AL + AD //ž   -----边界

我使用下面的代码

-(NSString *)uploadFileToServer:(NSString *)fileName fileData:(NSData *)file1Data
{
NSString *urlString =url.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---BOUNDARY";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSString *header = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"file",@"pic.jpg"];
[body appendData:[[NSString stringWithFormat:@"\r\n–%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:header] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:file1Data]];
[body appendData:[[NSString stringWithFormat:@"\r\n–%@–\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] ;
return returnString;
}

响应

"details": {

    "errors": {

      "file": "is required"
    }
  },
  "error": "Invalid files",

  "error_code": 4,

  "exc_class": "FAPIValidationError",

  "rc": false

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用alamofire?

Alamofire.upload(multipartFormData: { (multipartFormData) in
// put your data to multipart here                        
}, to: url) { (result) in

    switch result {
    case .success(let upload, _, _):

    upload.responseJSON { response in

        switch response.result {
        case .success(let json):
        break:    
        case .failure(_):
        break:    
        }
    }
    case .failure(_):
    break:
    }
}