如何将图像上传到服务器?使用multipart?

时间:2018-03-26 09:12:22

标签: ios objective-c swift

如何将图片上传到服务器?在下面的代码中,字符串正在上传,但是在获取用户数据时图像没有上传到显示为空的服务器

 let url = URL(string: "http://findlogics.in/school-master/index.php?api/manage_profile/update_profile_info")!
    var request = URLRequest(url : url)
    request.httpMethod = "POST"
    let boundary = "---------------------------14737809831466499882746641449"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let postData = NSMutableData()

    postData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    let sringDataParameter = "student_id"
    let string = "17"
    postData.append("Content-Disposition: form-data; name=\"\(sringDataParameter)\"\r\n\r\n\(string)".data(using: String.Encoding.utf8)!)

    postData.append("\r\n".data(using: String.Encoding.utf8)!)
    postData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)

    postData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    let sringDataParameter1 = "phone"
    let string1 = "9866325787"
    postData.append("Content-Disposition: form-data; name=\"\(sringDataParameter1)\"\r\n\r\n\(string1)".data(using: String.Encoding.utf8)!)

    postData.append("\r\n".data(using: String.Encoding.utf8)!)
    postData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)



    let bannerImageParameter = "userfile"
    postData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    postData.append("Content-Disposition: form-data; name=\(bannerImageParameter); filename=imagename.png\r\n".data(using: String.Encoding.utf8)!)

    postData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    postData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
    postData.append(pictureData as Data)
    postData.append("\r\n".data(using: String.Encoding.utf8)!)
    postData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)


    request.httpBody = postData as Data

2 个答案:

答案 0 :(得分:0)

这对我有用。

       func upload() {
                let url = "YOUR_SERVER_URL"

                Alamofire.upload(
                    multipartFormData: { multipartFormData in
                        for (key, value) in parametersForAdding {
                            let stringValue = "\(value)"
                            multipartFormData.append(stringValue.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
                        }

                        for (index, image) in self.selectedPhotosAsImage.enumerated() {
                             // these are for compressed image size
                            if let imageData = compressImage(image: image) {
                                multipartFormData.append(imageData, withName: "file\(index)", fileName: "\(index)", mimeType: "image/jpeg")
                            }

                            // these are for original image size
        //                    if let imageData = UIImageJPEGRepresentation(image, 0.6) {
        //                        multipartFormData.append(imageData, withName: "file\(index)", fileName: "\(index)", mimeType: "image/jpeg")
        //                    }
                        }
                    },
                    to: url) { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):

                            upload.uploadProgress(closure: { (progress) in
                                print(progress)
                            })

                            upload.responseJSON { response in

                                // If the request to get activities is successful, store them
                                if response.result.isSuccess{
                                    print(response.debugDescription)

                                    self.navigationController?.popViewController(animated: true)
                                } else {
                                    let errorMessage = "ERROR MESSAGE: "
                                    print(errorMessage) //Contains General error message or specific.
                                    print(response.debugDescription)
                                }
                            }
                        case .failure(let encodingError):
                            print("FALLE ------------")
                            print(encodingError)
                        }
                }
            }

答案 1 :(得分:0)

请使用Alamofire

试试
func dataToServer(){        
Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(imageData, withName: "imageDataParam", fileName: "image.jpeg", mimeType: "image/jpeg")



        }, to:"\(appDelegate.baseURL)/upload-document",
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                        if response.result.isSuccess
                        {
                            let jsonDict = response.result.value as! NSDictionary
                            AFWrapperClass.svprogressHudDismiss(view: self)
                            let dic:NSDictionary = jsonDict as NSDictionary
                            if (dic.object(forKey: "code")) as! String == "1"
                            {
                               //Success
                        }else
                        {
                            let error : NSError = response.result.error! as NSError

                        }
                    }
                    upload.uploadProgress(closure: {
                        progress in
                        print(progress.fractionCompleted)
                    })
                case .failure(let encodingError):
                    print(encodingError)

                }
        })
    }