2016-10-31 2 views
1

Alamofireに画像をアップロードしようとしている間、私は3日間立ち往生しています。アイデアはAlamofireがいくつかのPHPコードでサーバにそれを送るということです。さまざまな場所で試してみると、いくつかのコードがうまくいくはずですが、Alamofireのサーバー側のドキュメントは恐ろしいものです。Alamofireを使ってすぐに画像をアップロードすることはできません。

let imageData = UIImageJPEGRepresentation(imageFile!, 1)! 

Alamofire.upload(
     multipartFormData: { multipartFormData in 
      multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "file/jpeg") 
     }, 
     to: "https://someadress.com/post/upload.php", 
     encodingCompletion: { encodingResult in 
      switch encodingResult { 
      case .success(let upload, _, _): 
       upload.responseJSON { response in 
        debugPrint(response) 
       } 
      case .failure(let encodingError): 
       print(encodingError) 
      } 
     } 
    ) 

これは、サーバに画像をアップロードする必要がありますが、私が持っている:

迅速3への最近の更新はあまり賢いお答えしていません...ここで

は私スウィフト3のコードですサーバー上に保存されているイメージを適切に取得する方法がわかりません。サーバーはファイルの新しい情報を生成するので、ファイルの情報は実際には必要ありません。その名前をアプリに送り返す必要があります。

私はSwift 3とPHPでJSONを扱う方法を知っています。これは前に行っています。私は基本的な情報を元に戻しているので、少なくとも何かがサーバーにアップロードされることも確かに知っています。

以下のPHPコードはほとんど確かに良くありませんが、ほとんどのテストでした。事前に任意の助け

<?php 
// get the file data 
$fileData = file_get_contents('php://input'); 

// sanitize filename 
$fileName = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).])", '', $fileData); 
// save to disk 

$fileLocation = "../images/" . $fileName; 
file_put_contents($fileLocation, $fileData); 

if (empty($fileData)) { 
    $response = array("error" => "no data"); 
} 
else { 
    $response = array("error" => "ok " . $fileName); 
} 

echo json_encode($response); 
?> 

感謝:)

P.S.私は素早くすることができますので、穏やかにしてください;)

+0

私はそれを修正!私は数日でこれをドキュメントに追加しようとしています! – NotBramKorsten

+0

こんにちは、地域社会に役立つ解決策を教えてください。ありがとう – Sam

+0

@Sam Done!誰かを助けることを願っています! – NotBramKorsten

答えて

5

さて、sooo。私はそれを考え出した。 AlamofireはPHPの$_FILESの機能を使用していることが判明しました。これについては何も言及されていないので、私は物事をクリアしようとする人にさせてください。ここにコメント付きの完全なPHPコードがあります。

<?php 

// If the name of the image is not in this array, the app didn't post anything. 
if (empty($_FILES["image"])) { 
    // So we send a message back saying there is no data... 
    $response = array("error" => "nodata"); 
} 
// If there is data 
else { 
    $response['error'] = "NULL"; 
    // Setup a filename for the file. Uniqid can be changed to anything, but this makes sure 
    // that every file doesn't overwrite anything existing. 
    $filename = uniqid() . ".jpg"; 
    // If the server can move the temporary uploaded file to the server 
    if (move_uploaded_file($_FILES['image']['tmp_name'], "../images/" . $filename)) { 
     // Send a message back saying everything worked! 
     // I also send back a link to the file, and the name. 
     $response['status'] = "success"; 
     $response['filepath'] = "https://i335731.iris.fhict.nl/hypeAPI/images/" . $filename; 
     $response['filename'] = "".$_FILES["file"]["name"]; 

} else{ 
    // If it can't do that, Send back a failure message, and everything there is/should be form the message 
    // Here you can also see how to reach induvidual data from the image, such as the name. 
    $response['status'] = "Failure"; 
    $response['error'] = "".$_FILES["image"]["error"]; 
    $response['name'] = "".$_FILES["image"]["name"]; 
    $response['path'] = "".$_FILES["image"]["tmp_name"]; 
    $response['type'] = "".$_FILES["image"]["type"]; 
    $response['size'] = "".$_FILES["image"]["size"]; 
    } 
} 

// Encode all the responses, and echo them. 
// This way Alamofire gets everything it needs to know 
echo json_encode($response); 
?> 

これは基本的にそれです。あなたがしなければならないのは、Alamofireリクエストで送信する名前が '$ _FILES'括弧の間の名前と一致することだけです。一時名は、Alamofireのファイル名です。

ここにSwift 3コードがあります。

// Note that the image needs to be converted to imagedata, in order to work with Alamofire. 
let imageData = UIImageJPEGRepresentation(imageFile!, 0.5)! 

Alamofire.upload(
      multipartFormData: { multipartFormData in 
       // Here is where things would change for you 
       // With name is the thing between the $files, and filename is the temp name. 
       // Make sure mimeType is the same as the type of imagedata you made! 
       multipartFormData.append(imageData, withName: "image", fileName: "image.jpg", mimeType: "image/jpeg") 
      }, 
      to: "https://i335731.iris.fhict.nl/hypeAPI/post/upload.php", 
      encodingCompletion: { encodingResult in 
       switch encodingResult { 
       case .success(let upload, _, _): 
        upload.responseJSON { response in 
         if let result = response.result.value { 
          // Get the json response. From this, we can get all things we send back to the app. 
          let JSON = result as! NSDictionary 
          self.imageServerLocation = JSON.object(forKey: "filepath") as? String 
          debugPrint(response) 
         } 
        } 
       case .failure(let encodingError): 
        print(encodingError) 
       } 
      } 
     ) 

私はこれが同じ問題を抱えている多くの人に役立つことを願っています!見つからないことや何か知りたいことがあれば教えてください!

0

スウィフト3

func uploadImage(_ imageFileUrl:URL, encodeCompletion: ((Alamofire.SessionManager.MultipartFormDataEncodingResult) -> Void)?){ 
    let fileName = "imageName.jpg" 
    let headers = ["contentType":"image/jpeg"] 
     Alamofire.upload(multipartFormData: { (multipartFormData) in 
      multipartFormData.append(imageFileUrl, withName: fileName) 
     }, to: "uploadPath", method: .post, headers: headers, encodingCompletion: encodeCompletion) 
    } 
関連する問題