如何将图像上传到服务器?使用多部分?

Posted

技术标签:

【中文标题】如何将图像上传到服务器?使用多部分?【英文标题】:how to upload a image to server? using multipart? 【发布时间】:2018-03-26 09:12:22 【问题描述】:

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

 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

【问题讨论】:

Upload image to server - Swift 3的可能重复 post image to server in iphone的可能重复 【参考方案1】:

这对我有用。

       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)
                        
                
            

【讨论】:

@Moritz,正如我所写,这对我有用。没有复制,这些是我用于我的项目的。【参考方案2】:

请使用 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)

                
        )
    

【讨论】:

以上是关于如何将图像上传到服务器?使用多部分?的主要内容,如果未能解决你的问题,请参考以下文章

使用多部分和 Alamofire 上传图像

Android 相机图像未上传到服务器。使用多部分数据 Http post

如何上传文件多部分alamofire swift5?

如何以多部分形式将画布图像上传到 java servlet?

将图像上传到服务器android

如何使用 NodeJS 将文件或图像上传到服务器