2016-09-27 102 views
2

使用Xcode 8,Swift 3和PHP。xcode 8 swift 3圖像文件不會上傳到服務器

Xcode和PHP運行沒有錯誤。

爲什麼不將模擬器中的displayPic.image保存到服務器的pic1-1.png中?所有出現的都是空白文件。

的Xcode:

@IBAction func sendToServer(_ sender: UIButton) { 

    let url = NSURL(string: "http://www.example.com/picSaver.php") 

    var request = URLRequest(url: url! as URL) 

    request.httpMethod = "POST" 

    var boundary = generateBoundaryString() 

    request.setValue("multipart/form-data; boundary=\(boundary)", 
forHTTPHeaderField: "Content-Type") 

    if (displayPic.image == nil) 
    { return } 

    let image_data = UIImagePNGRepresentation(displayPic.image!) 
    var body = NSMutableData() 
    let fname = "porch-167.png" 
    let mimetype = "image/png" 

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) 
    body.append("Content-Disposition:form-data; 
name=\"photo\"\r\n\r\n".data(using: String.Encoding.utf8)!) 
    body.append("Incoming\r\n".data(using: String.Encoding.utf8)!) 
    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) 
    body.append("Content-Disposition:form-data; name=\"file\"; 
filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!) 
    body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: 
String.Encoding.utf8)!) 
    body.append(image_data!) 
    body.append("\r\n".data(using: String.Encoding.utf8)!) 
    body.append("--\(boundary)--\r\n".data(using: 
String.Encoding.utf8)!) 

    request.httpBody = body as Data 

    let session = URLSession.shared 

    let task = session.dataTask(with: request as URLRequest) { 
     (
     data, response, error) in 

     guard let _:Data = data, let _:URLResponse = response , error 
== nil else { 
      print("error") 
      return 
      } 

     let dataString = String(data: data!, encoding: 
String.Encoding(rawValue: String.Encoding.utf8.rawValue)) 
     print(dataString) 

     } 

    task.resume() 
} 

} 

func generateBoundaryString() -> String { 

return "Boundary-\(NSUUID().uuidString)"  
} 

picSaver.php

<?php 
$p=$_REQUEST["filename"] 
move_uploaded_file($p["tmp_name"], pic1-1.png); 

$data=Array("Reply"=>"Image saved at server"); 
echo json_encode($data); 
?> 

是 「文件名」 正確的參數爲$ P $ _REQUEST的要求嗎?

+0

好的,我會試試。 – Aleric

+0

我添加了php腳本,並用!解開了p。沒有錯誤,但保存到服務器的jpeg是空白的。有什麼建議麼。 – Aleric

+0

任何建議。 @Jakub – Aleric

回答

1

它現在工作完美無瑕。將$ _REQUEST更改爲$ _FILES,將「filename」更改爲「file」

<?php 
$p=$_FILES["file"] 
move_uploaded_file($p["tmp_name"], "pic1-1.png"); 

$data=Array("Reply"=>"Image saved at server"); 
echo json_encode($data); 
?>