如何在Objective c ios中使用multipart上传图像?

时间:2017-07-18 06:20:37

标签: ios objective-c

我已尝试过此代码,但无法正确上传文件。

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = @"file";

// the server url to which the image (or video) is uploaded. Use your server url here
url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%d",baseURL,@"posts/post/update/",createPostObject.PostID]];    


// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:120];
[request setHTTPMethod:@"POST"];
[request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

[request setURL:url];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

if([[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"]){

    [request setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"] forHTTPHeaderField:AccessTokenKey];

}

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in self.postParams) {

    NSLog(@"param is %@",param);

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param]             dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [self.postParams objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add video file name to body

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"file.mp4\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: video/mp4\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
  //  [body appendData:self.dataToPost];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];



// setting the body of the post to the request
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);

NSURLSessionConfiguration * backgroundConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"backgroundtask1"];

NSURLSession *backgroundSeesion = [NSURLSession sessionWithConfiguration: backgroundConfig delegate:self delegateQueue: [NSOperationQueue mainQueue]];

5 个答案:

答案 0 :(得分:0)

我找到了解决方案

-(void)multipleimageandstring
{
    NSString *urlString=@"http://52.221.232.12/bca/banner_add.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

    // file
    float low_bound = 0;
    float high_bound =5000;
    float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);//image1
    int intRndValue = (int)(rndValue + 0.5);
    NSString *str_image1 = [@(intRndValue) stringValue];

    UIImage *chosenImage1=[UIImage imageNamed:@"air.png"];

    NSData *imageData = UIImageJPEGRepresentation(chosenImage1, 90);
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"banner_image\"; filename=\"%@.png\"\r\n",str_image1] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"banner_title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Nilesh" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"admin_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"1" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    // close form
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // set request body
    [request setHTTPBody:body];

    //return and test
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", returnString);

}

答案 1 :(得分:0)

Swift 3.0中的

func addAppointment() -> Void {

        let parameters = ["user_id":"68","subject":txtSubject.text!,"admin_id":"21","appointment_by":"1","appoinment_date":txtAppointmentDate.text!,"appoinment_time":txtAppointmentTime.text!]

        EZLoadingActivity.show("", disableUI: true)
        Alamofire.upload(multipartFormData: { multipartFormData in


            multipartFormData.append(self.imageData as Data, withName: "appointment_attachment",fileName: "file.jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        },
                         to:"http://52.221.232.10/BCA/appointment_booking.php")
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    print(response.result.value!)
                    EZLoadingActivity.hide()
                    let dataDic = response.result.value! as! NSDictionary
                    let msg = dataDic.value(forKey: "message")
                    let alert = UIAlertController(title: "", message: msg as? String, preferredStyle: .alert)
                    let alertActionOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    alert.addAction(alertActionOk)
                    self.present(alert, animated: true, completion: nil)

                }

            case .failure(let encodingError):
                print(encodingError)
                let msg = encodingError
                let alert = UIAlertController(title: "", message: msg as? String, preferredStyle: .alert)
                let alertActionOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
                alert.addAction(alertActionOk)
                self.present(alert, animated: true, completion: nil)
                EZLoadingActivity.hide()
            }
        }

    }

答案 2 :(得分:0)

使用Alamofire

在Swift 3.0中获取多张图片

func addCaseDetail() -> Void {

            let parameters = ["user_id":"68","subject":txtSubject.text!,"admin_id":"21","added_by":"1","case_title":txtTitle.text!,"case_description":txtDescription.text!]

        EZLoadingActivity.show("", disableUI: true)
        Alamofire.upload(multipartFormData: { multipartFormData in


            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)

            }

            for  i in (0..<self.choosenImageArray.count){

                var imageData = Data()
                let resizedImage = self.resizeImage(image: self.choosenImageArray[i] as! UIImage, targetSize: CGSize(width:500.0 ,height:500.0))
                imageData = (UIImagePNGRepresentation(resizedImage )! as NSData) as Data

                  multipartFormData.append(imageData as Data, withName: "case_image[]",fileName: "file\(i).png", mimeType: "image/png")

            }
        },
                         to:"http://52.221.232.10/CBCA/case_details_add.php")
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    print(response.result.value!)
                    EZLoadingActivity.hide()

                    let dataDic = response.result.value! as! NSDictionary
                    let msg = dataDic.value(forKey: "message")
                    let alert = UIAlertController(title: "", message: msg as? String, preferredStyle: .alert)
                    let alertActionOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    alert.addAction(alertActionOk)
                    self.present(alert, animated: true, completion: nil)

                }

            case .failure(let encodingError):
                print(encodingError)
                let msg = encodingError
                let alert = UIAlertController(title: "", message: msg as? String, preferredStyle: .alert)
                let alertActionOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
                alert.addAction(alertActionOk)
                self.present(alert, animated: true, completion: nil)
                EZLoadingActivity.hide()
            }
        }

}

答案 3 :(得分:0)

在正常数据请求的swift 3.0中

let USER_LIST_FIRMWISE_URL = "\(BASE_URL2)user_list_firm_wise.php"

func userListFirmwiseRequest(firmid:String) -> URLRequest {
        let Url = URL(string: (utility?.USER_LIST_FIRMWISE_URL)!)
        var request = URLRequest(url: Url!)
        request.httpMethod = "POST"
        request.cachePolicy = .reloadIgnoringCacheData
        let paramString = "firm_id=\(firmid)"
        request.httpBody = paramString.data(using: String.Encoding.utf8)
        return request
    }


func getuserList() -> Void {

        var request = mainApp.reqRes?.userListFirmwiseRequest(firmid: firmID)
        request?.httpMethod = "POST"
        print("request")

        EZLoadingActivity.show("", disableUI: true)
        let task = URLSession.shared.dataTask(with: request!) { (data: Data?, response: URLResponse?, error: Error?) in

            DispatchQueue.main.async
                {
                    do {


                        guard let data = data, error == nil else {
                            print("Error=\(String(describing: error))")
                            return
                        }
                        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                            print("Status code should be 200, but is \(httpStatus.statusCode)")
                            print("Response String:\(String(describing: response))")
                        }

                        let jsonString = try? JSONSerialization.jsonObject(with: data, options: [])

                        guard let JsonObject = try? jsonString as AnyObject else{
                            return
                        }

                        guard let Success = try? JsonObject["success"] as! Int else{
                            return
                        }
                        print("Succee Resul :\(Success)")

                        if Success > 0{
                            guard let Message = try? JsonObject["message"] as Any else{
                                return
                            }

                            guard let JsonObjectForUser = try? Message as? AnyObject else {
                                return
                            }
                        }


                        let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary ?? nil

                        if let parseJSON = json {
                            let dataDic = parseJSON.value(forKey: "message") as! NSMutableArray


                            self.arrayUserNameList = dataDic.value(forKey: "user_name") as! [String]

                            self.arrayUserData = dataDic
                            print(self.arrayUserNameList)

                            self.picker.reloadAllComponents()
                            EZLoadingActivity.hide()
                        }
                    } catch{
                        print(error)
                        EZLoadingActivity.hide()
                    }
            }

        }

        task.resume()

    }

答案 4 :(得分:0)

用于通过URL会话,Swift 4.0上传多个图像

func callJSONMethod(_ methodName: String?, withFilePathArray imagePathArray: [String],imageDataArray: [Data], andParams params: [String : Any]?) {
        var imagePathArray = imagePathArray
        let params = params

            SVProgressHUD.show()

        let url = URL(string: Constant.shared.WEBSERVICE_URL)
        var request: URLRequest? = nil
        if let url = url {
            request = URLRequest(url: url)
        }
        request?.httpMethod = "POST"
        let boundary = "\("---------------------------14737809831466499882746641449")"
        let contentType = "multipart/form-data; boundary=\(boundary)"
        request?.addValue(contentType, forHTTPHeaderField: "Content-Type")

        var body = Data()
        var requestDict: [AnyHashable : Any] = [:]
        requestDict["method_name"] = methodName
       requestDict["body"] = params

        let jjson = try? JSONSerialization.data(withJSONObject: requestDict, options: [])
        let jsonString = String(data: jjson!, encoding: .utf8)!
        print(jsonString)

        if let data = "--\(boundary)\r\n".data(using: .utf8) {
            body.append(data)
        }
        let paramsFormat = "Content-Disposition: form-data; name=\"\("json")\"\r\n\r\n"
        if let data = "\(paramsFormat)".data(using: .utf8) {
            body.append(data)
        }
        if let data = "\(jsonString)".data(using: .utf8){
            body.append(data)
        }
        if let data = "\("\r\n")".data(using: .utf8) {
            body.append(data)
        }

        // file

        for i in 0..<imagePathArray.count {
            if let data = "--\(boundary)\r\n".data(using: .utf8) {
                body.append(data)
            }
            let filePath = imagePathArray[i] as? NSString
            let fileName = filePath?.lastPathComponent
            let strKeyName = "docName[]"
            if let data = "Content-Disposition: attachment; name=\"\(strKeyName)\"; filename=\"\(fileName ?? "")\"\r\n".data(using: .utf8) {
                body.append(data)
            }
            if let data = "\("Content-Type: application/octet-stream\r\n\r\n")".data(using: .utf8) {
                body.append(data)
            }
          let data = imageDataArray[i]
            body.append(data)
            if let data = "\("\r\n")".data(using: .utf8) {
                body.append(data)
            }
        }

        if let data = "--\(boundary)--\r\n".data(using: .utf8) {
            body.append(data)
        }
       let strBody = String(decoding: body, as: UTF8.self)
        print("body\(strBody)")
        //request?.httpBody = body
        let session = URLSession.shared

        request?.httpBody = body

        let task = session.dataTask(with: request!, completionHandler: { data, response, error -> Void in
           // print(response!)
            SVProgressHUD.dismiss()
            let strResponse = String(decoding: data!, as: UTF8.self)
            print("body\(strResponse)")
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]

                print(json.description)
                if methodName == Constant.shared.APPLY_OFFER_LETTER{
                    self.delegate?.passApplyOfferData!(data: json)
                }
            }catch {

                print("error" + self.debugDescription)

            }
        })
        task.resume()


    }