簡體   English   中英

Alamofire Multipart圖片上傳失敗

[英]Alamofire Multipart image upload failed

我使用multipart上傳圖像與Alamofire,但我構建並上傳它失敗這是我的快速代碼“

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(d1, withName: "file",fileName: "file.jpg", mimeType: "image/jpg")// d1 in let d1 = UIImageJPEGRepresentation(uiimage, 1)
    },
    to: "mysite/upload.php",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

和我的PHP代碼

$ip = $_SERVER['REMOTE_ADDR'];
$timestp = DATE("Y-m-d H:i:s");
$milliseconds = round(microtime(true) * 1000);
$image_name=date("dmyHis").$milliseconds.$psmemid.$psplace.$pscate.".jpg";
$imgpath = "../Image/";
$newname = $imgpath.$image_name;
$copied = copy($_FILES['club_image']['tmp_name'], $newname);
    $upload = $imgpath . basename($_FILES['club_image']['tmp_name']);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

和上傳后的日志是

[Response]: <NSHTTPURLResponse: 0x600000428f40> { URL: mysite/upload.php } { status code: 200, headers {
    Connection = "keep-alive";
    "Content-Length" = 0;
    "Content-Type" = "text/html";
    Date = "Thu, 13 Oct 2016 04:33:03 GMT";
    Server = nginx;
    Vary = "User-Agent";
    "X-Powered-By" = "PHP/5.3.29";
} }
[Data]: 0 bytes
[Result]: SUCCESS: 
[Timeline]: Timeline: { "Request Start Time": 498025982.810, "Initial Response Time": 498025982.843, "Request Completed Time": 498025983.432, "Serialization Completed Time": 498025983.432, "Latency": 0.033 secs, "Request Duration": 0.622 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.622 secs }

感謝你的幫助。

您在請求中發送錯誤的文件名。

Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(d1, withName: "club_image",fileName: "file.jpg", mimeType: "image/jpg")// d1 in let d1 = UIImageJPEGRepresentation(uiimage, 1)
        },
    to:"mysite/upload.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)  
            }

        case .failure(let encodingError):
            print(encodingError)  
        }
    }
func imageUpload(image : UIImage, parameter: NSDictionary?, completionHandler: @escaping (_ uploadStatus : MultipartUploadStatus) -> Void) {

    let uploadPath : String = "your image Upload API path here"
    let imgData : Data = UIImageJPEGRepresentation(image.fixOrientation(), 1.0)!


    print("API : \(uploadPath)")
    var appVersion: String? = ""
    if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
        appVersion = version
    }

    if CommonUnit.isUserAlreadyLogIn() {
        Constant.Common.headerToken = UserDefaults.standard.value(forKey: "HeaderToken") as! String
    }

    let headers: HTTPHeaders = [
        "header_token": Constant.Common.headerToken,
        "device_type": "1",
        "device_token": Constant.Common.DeviceToken,
        "app_version": appVersion!,
        "app_type":"1",
        "Accept": "application/json"
    ]


    var apiParams : NSDictionary!

    if (parameter != nil)
    {
        apiParams = convertDictToJson(dict: parameter! as NSDictionary)
    }

    print("Params : \(String(describing: apiParams)) and Header : \(headers)")

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(imgData, withName: "filedata", fileName: "filedata.jpg", mimeType: "image/jpeg")
        print("mutlipart 1st \(multipartFormData)")
        if (apiParams != nil)
        {
            for (key, value) in apiParams! {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key as! String )
            }
            print("mutlipart 2nd \(multipartFormData)")
        }
    }, to:uploadPath, method:.post, headers:headers)
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (Progress) in
                completionHandler(.uploading(progress: Float(Progress.fractionCompleted)))
            })

            upload.responseJSON { response in

                if let JSON = response.result.value {
                    completionHandler(.success(progress: 1.0, response: JSON as! NSDictionary))
                }
            }
        case .failure(let encodingError):
            print(encodingError)
            completionHandler(.failure(error: encodingError as NSError))
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM