Swift图像上传到PHP发送TMP文件而不是Image

时间:2017-07-23 20:56:58

标签: php swift uiimagepickercontroller uiimagejpegrepresentation uiimagepngrepresentation

我有一个应用程序,我从相机拍照,它必须发送到服务器(PHP),问题是,当我上传图片时,服务器只接收一个tmp文件。我怎么解决这个问题?我提前感谢你的回答。我的代码如下:

拍摄照片按钮

    @IBAction func tomarFoto(_ sender: Any) {
    indicadorActividad.startAnimating()
    let image = UIImagePickerController()
    image.delegate = self

    image.sourceType = UIImagePickerControllerSourceType.camera

    image.allowsEditing = true

    self.present(image, animated: true){
    }
}

更改图片尺寸

@IBAction func tomarFoto(_ sender: Any) {
    indicadorActividad.startAnimating()
    let image = UIImagePickerController()
    image.delegate = self

    image.sourceType = UIImagePickerControllerSourceType.camera

    image.allowsEditing = true

    self.present(image, animated: true){
    }
}

ImagePicker

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {

        imageView.image = resizedImage(image: image, newWidth: 300, newHeight: 300)
        } else {
        //Algo
        }
        //Detenemos el indicador y se cierra la ventana de la camara/galeria
        self.indicadorActividad.stopAnimating()
        self.dismiss(animated: true, completion: nil)
        }


func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
    }

以下函数拍摄照片并将其上传到PHP服务器,我认为错误可能就在这里。 上传到服务器

func subirFotoRequest(){
    let url = URL(string: "http://192.168.0.155/BolsaTrabajo/imagen.php")

    let request = NSMutableURLRequest(url: url!)
    request.httpMethod = "POST"

    let boundary = generateBoundaryString()

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

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

    let image_data = UIImagePNGRepresentation(imageView.image!)

    if(image_data == nil)
    {
        return
    }

    let body = NSMutableData()
    indicadorActividad.startAnimating()

    let fname = "test.png"
    let mimetype = "image/png"


    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append("hi\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 = URLSession.shared.dataTask(with: request as URLRequest) {            (
        data, response, error) in

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

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

        print(dataString)
        //self.indicadorActividad.stopAnimating()



        do {
        DispatchQueue.main.async(execute: {
            self.indicadorActividad.stopAnimating()

            self.imageView.image = nil;
            });
        }
        catch{
            //Errores
        }


    }
    task.resume()       
}    

func generateBoundaryString() -> String
{
    return "Boundary-\(UUID().uuidString)"
}

最后一段代码是我的PHP脚本。 PHP文件[已更新]

PHP文件现在以相应的格式上传图片,唯一的问题是,它会覆盖我之前的图片。我怎样才能防止这种情况发生?我想的可能是设置一个名字,这个名字将会改变我的快速课程中的每张图片。代码更新如下以前的代码已注释

//$ruta =  "Imagenes/";
  //if($_FILES["file"]["name"] !== ""){
    //  mkdir($ruta, 0777, true);
     // move_uploaded_file($_FILES["file"]["name"], $ruta.'/'. 
  //basename($_FILES["file"]["name"]));
   // echo "subido";
   //}


$fichero_subido = $dir_subida . basename($_FILES['file']['name']);

echo '<pre>';

   if(move_uploaded_file($_FILES['file']['tmp_name'], $fichero_subido)){
    echo "El fichero es válido y se subó con éxito \n";
   }
      else{
          echo "Posible ataque de subida de ficheros\n";
      }

  echo 'Más información de depuración: ';

print_r($_FILES);   

0 个答案:

没有答案