I have an App where I take a picture from the camera and it has to be send to a server (PHP), the problem is, that when I upload the picture, the server only receives a tmp file instead. How can I solve this? I thank your answers in advance. My code is the following:
Take Photo Button
@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){
}
}
Change size of picture
@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)
}
The following function takes the picture and Uploads it to the PHP server, I think the error might be here. Upload to server
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)"
}
And the final block of code is my PHP script. PHP File [UPDATED]
PHP file now uploads the picture in the respective format, the only problem is, it overrides my previous picture. How can I prevent this from happen? I was thinking probably by setting a name that will change for every picture in my swift class. Code updated is the following Previous code is commented:
//$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);