Foros del Web » Programando para Internet » Android »

Subir imagen a server + php

Estas en el tema de Subir imagen a server + php en el foro de Android en Foros del Web. Hola, como estan?? Queria consultarles sobre los metodos usados para subir imagenes a un servidor. Es mejor el metodo POST o con PHP? Yo he ...
  #1 (permalink)  
Antiguo 23/06/2012, 16:37
 
Fecha de Ingreso: julio-2008
Ubicación: Buenos Aires, Mar del plata
Mensajes: 250
Antigüedad: 15 años, 9 meses
Puntos: 2
Subir imagen a server + php

Hola, como estan??
Queria consultarles sobre los metodos usados para subir imagenes a un servidor.
Es mejor el metodo POST o con PHP?

Yo he usado lo siguiente, y todavia no logro hacerlo funcionar...alguno lo ha implementado de otra manera?

Código:
try {
		HttpClient httpClient = new DefaultHttpClient();  
		HttpContext localContext = new BasicHttpContext();  
		// here, change it to your php;  
		HttpPost httpPost = new HttpPost("http://www.xxxxxxxxxxxxxxx.com.ar/archivos/ImageUtil.php");  
		MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
		bitmap = BitmapFactory.decodeFile("test111.jpg");  
                Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);  
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
		bmpCompressed.compress(CompressFormat.JPEG, 100, bos);  
		byte[] data = bos.toByteArray();  
				  
		// sending a String param;  
		entity.addPart("myParam", new StringBody("my value"));  
		// sending a Image;  
		// note here, that you can send more than one image, just add another param, same rule to the String;  
		entity.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));  
		httpPost.setEntity(entity);  
		HttpResponse response = httpClient.execute(httpPost, localContext);  
		BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));  
		String sResponse = reader.readLine();  
				  
		} catch (Exception e) {  
				  Log.v("myApp", "Some error came up");  
				  }

Código PHP:
Ver original
  1. <?php
  2. class ImageUtil{
  3.     const uploadDir = "img";
  4.     const allowedExtensions = "jpg, jpeg, gif, png";
  5.     const maxSize = 2; //MB
  6.     const maxWidth = 1024;
  7.     const maxHeight = 1024;
  8.    
  9.     private static function validExtension($extension){
  10.         $allowedExtensions = explode(", ", ImageUtil::allowedExtensions);
  11.         return in_array($extension, $allowedExtensions);
  12.     }
  13.    
  14.     private static function validSize($size){
  15.         return $size<=ImageUtil::maxSize * pow(2,10);
  16.     }
  17.    
  18.     private static function validDimensions($width, $height){
  19.         return $width<ImageUtil::maxWidth && $height < ImageUtil::maxHeight;
  20.     }
  21.    
  22.     private static function uploadedFile($file, $newFile){
  23.         return move_uploaded_file($file, ImageUtil::uploadDir.'/'.$newFile);
  24.     }
  25.    
  26.     public static function uploadImage($file, $newName){
  27.         $extension = pathinfo($file['name']);
  28.         $extension = $extension[extension];
  29.        
  30.         // check extension
  31.         if (!ImageUtil::validExtension($extension))
  32.             throw new InvalidExtensionException();
  33.        
  34.         // check dimensions
  35.         list($width, $height, $type, $w) = getimagesize($_FILES['userfile']['tmp_name']);
  36.         if (!ImageUtil::validDimensions($width, $height))
  37.             throw new InvalidDimensionsException();
  38.        
  39.         // check size
  40.         if (!ImageUtil::validSize($file['size']))
  41.             throw new InvalidSizeException();
  42.        
  43.         // move to needed location
  44.         if (!ImageUtil::uploadedFile($file['tmp_name'], $newName.".".$extension))
  45.             throw new UnableToUploadException();
  46.        
  47.         return true;
  48.     }
  49. }
  50.  
  51. class InvalidExtensionException extends Exception {
  52.     protected $message = 'Extension is invalid';   // exception message
  53. }
  54. class InvalidDimensionsException extends Exception {
  55.     protected $message = 'Image dimensions are invalid';   // exception message
  56. }
  57. class InvalidSizeException extends Exception {
  58.     protected $message = 'Size is invalid';   // exception message
  59. }
  60. class UnableToUploadException extends Exception {
  61.     protected $message = 'Unable to upload file';   // exception message
  62. }
  63. ?>

Muchas gracias!!
  #2 (permalink)  
Antiguo 24/06/2012, 12:51
Avatar de javih  
Fecha de Ingreso: agosto-2011
Mensajes: 201
Antigüedad: 12 años, 8 meses
Puntos: 12
Respuesta: Subir imagen a server + php

Cita:
Es mejor el metodo POST o con PHP?
POST Y GET son dos métodos de PHP.
  #3 (permalink)  
Antiguo 24/06/2012, 13:46
Avatar de javih  
Fecha de Ingreso: agosto-2011
Mensajes: 201
Antigüedad: 12 años, 8 meses
Puntos: 12
Respuesta: Subir imagen a server + php

Mira una simple búsqueda en el Google, 4 métodos.

http://www.coderzheaven.com/2012/04/...rver-method-4/

Saludos.

PD: No me envíes preguntas por privado porque no las leo hasta a saber cuando y porque no tengo tiempo para responderlas y tampoco sé (o sabía) como se hace, al final se las respondí al moderador (por error). Y porque los foros no funcionan así, la ayuda no es solo para ti, sino para más usuarios que la puedan necesitar. Así que para que no pierdas el tiempo y/o me lo hagas perder a mí, pregunta por el foro.
  #4 (permalink)  
Antiguo 24/06/2012, 16:40
 
Fecha de Ingreso: julio-2008
Ubicación: Buenos Aires, Mar del plata
Mensajes: 250
Antigüedad: 15 años, 9 meses
Puntos: 2
Respuesta: Subir imagen a server + php

Gracias!

Si, con ese tutorial tambien probe pero me da "Source File Does not exist".
Voy a seguir intentando y analizando el error.
Me temo que sea problema con el emulador tambien...
  #5 (permalink)  
Antiguo 24/06/2012, 16:43
 
Fecha de Ingreso: julio-2008
Ubicación: Buenos Aires, Mar del plata
Mensajes: 250
Antigüedad: 15 años, 9 meses
Puntos: 2
Respuesta: Subir imagen a server + php

Se supone que si elegimos la opcion de pasar una imagen dentro de R.drawable, el proceso seria:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = (BitmapDrawable)getResources().getDrawable(R.drawa ble.simag)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
photo = baos.toByteArray();
int response= uploadFile(photo.toString());

Y luego que esta en String, se lo paso a la funcion.
Creo que ese es el error.

Por lo menos, tengo identificado el problema..

Etiquetas: imagenes+php, server+php, upload
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:21.