Camera and gallery image upload by alamofire in swift 3

那年仲夏 提交于 2019-12-13 03:20:59

问题


Hi there i have spent more than 20 hours to figure out how to upload image from my app to server, image which i want to upload could be either taken from camera or photo roll..... here is my code which does show progress of uploading but doesnt reach to server and thus gets negative response form server.. please help me..

  Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(UIImageJPEGRepresentation(image, 0.1)!, withName: imageName)
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        },
                         to: URL_USER_PROFILE_IMG_UPLOAD)
        { (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)
            }
        }

and my server code is in PHP as this

    <?php

// Path to move uploaded files
$target_path = "profile-photos/";

// array for final json respone
$image_upload = array();
 $server_ip ="00.000.000.000";
//gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip .'/'.'folder2017'.'    /'.'webser'.'/'. $target_path;



if(isset($_FILES['image']['name'])) {
$target_path=$target_path.$_FILES['image']['name'];
   if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path))         {
        $image_upload=array('path'=>$file_upload_url,'response_code'=>1);
        echo json_encode($image_upload);
  }
  } else {

  $image_upload=array('response_code'=>0);
  echo json_encode($image_upload);
  }



?>

回答1:


Try this:

Replace

multipartFormData.append(UIImageJPEGRepresentation(image, 0.1)!, withName: imageName)

With

let imgData = UIImageJPEGRepresentation(image!, 1.0)!
multipartFormData.append(imgData, withName: "image", fileName: "image.jpg", mimeType: "image/jpg")


来源:https://stackoverflow.com/questions/46039567/camera-and-gallery-image-upload-by-alamofire-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!