Foros del Web » Programación para mayores de 30 ;) » Java »

[SOLUCIONADO] Guardar imagen recibida dropzone

Estas en el tema de Guardar imagen recibida dropzone en el foro de Java en Foros del Web. Hola a todos. Necesito guardar en disco una imagen subida desde el navegador. Lo que estamos utilizando para enviar los ficheros es el plugin dropzone ...
  #1 (permalink)  
Antiguo 09/08/2016, 09:09
 
Fecha de Ingreso: marzo-2008
Mensajes: 94
Antigüedad: 18 años, 6 meses
Puntos: 3
Guardar imagen recibida dropzone

Hola a todos.

Necesito guardar en disco una imagen subida desde el navegador. Lo que estamos utilizando para enviar los ficheros es el plugin dropzone. El plugin se integra y funciona correctamente el problema es cuando en el servidor intento recuperar la imagen para guardarla en disco.

He hecho cosas parecidas sin ningún problema con ficheros en base 64, esto debería de ser parecido pero me estoy rompiendo la cabeza con algo que debo de estar haciendo mal.

Añadimos la imagen y el plugin lanza la petición post con lo siguiente.

Cita:
-----------------------------298031368414422
Content-Disposition: form-data; name="file"; filename="bronson.jpg"
Content-Type: image/jpeg

ÿØÿá�ÞExif��II*���������V�������^���(� ������1�*���f���2��������i‡����¤���� ���ð�
���������Adobe Photoshop Lightroom 5.7 (Macintosh)�2015:09:10 20:56:08��������0230������
������2015:08:28 10:01:04�ÿí�ŽPhotoshop 3.0�8BIMí������ð�����ð����8BIM�����,Z� %G���
>�20150828?� 100104-07008BIM
�������8BIM%�����«n_6 @êW�zÏlýŸOÿâ XICC_PROFILE��� HLino��mntrRGB XYZ Î�� ��1��acspMSFT��
��IEC sRGB��������������öÖ�����Ó-HP �����������������������������������������������cp rt��P���3desc
��„���lwtpt��ð���bkpt�����rXYZ�����gXYZ�� ,���bXYZ��@���dmnd��T���pdmdd��Ä���ˆvued ��L
���†view��Ô���$lumi��ø���meas�� ���$tech��0��� rTRC��<�� gTRC��<�� bTRC��<�� text����Copyright
(c) 1998 Hewlett-Packard Company��desc�������sRGB IEC61966-2.1�����������sRGB IEC61966-2.1�������
�������������������������������������������X YZ ������óQ����ÌXYZ ����������������XYZ ������o¢��8õ�
��XYZ ������b™��·…��ÚXYZ ������$ ��„��¶Ïdesc�������IEC http://www.iec.ch�����������IEC http://www
.iec.ch������������������������������������������� ���desc�������.IEC 61966-2.1 Default RGB colour space
- sRGB�����������.IEC 61966-2.1 Default RGB colour space - sRGB����������������������desc�������,Reference
Viewing Condition in IEC61966-2.1�����������,Reference Viewing Condition in IEC61966-2.1�����������
���������������view�����¤þ�_.�Ï�íÌ� �\ž��� XYZ �����L V�P���Wçmeas������������������������
�����sig ����CRT curv�����������
�����#�(�-�2�7�;�@�E�J�O�T�Y�^�c�h�m�r�w�|���†�‹���•�š�Ÿ�¤�© �®�²�·�¼�Á�Æ�Ë�Ð�Õ�Û�à�å�ë�ð�ö�û

%+28>ELRY`gnu|ƒ‹’š¡©±¹ ÁÉÑÙáéòú &/8AKT]gqz„Ž˜
¢¬¶ÁËÕàëõ� !-8COZfr~Š–¢®ºÇÓàìù -;HUcq~Œš¨¶ÄÓáðþ

+:IXgw†–¦µÅÕåö'7HYj{Œ� ¯ÀÑãõ+=Oat†™¬¿Òåø 2FZn
‚–ª¾Òçû  % : O d y � ¤ º Ï å û

'
=
T
j
�
˜
®
Å
Ü
ó " 9 Q i € ˜ ° È á ù  * C \ u Ž § À Ù ó


&
@
Z
t
Ž
©
Ã
Þ
ø.Id›¶Òî %A^z–³Ïì &Ca~›¹×õ1OmŒªÉè&Ed„£Ãã #Ccƒ¤
Åå'Ij‹*Îð4Vx›½à&Il�²Öú Ae‰®Ò÷@eНÕú Ek‘·Ý*Qwž
Åì;cвÚ*R{£ÌõGp™Ãì@j” ¾é>i”¿ê  A l ˜ Ä ð!!H!u!¡!Î!û"'"U"‚"¯"Ý#

#8#f#”#Â#ð$$M$|$«$Ú% %8%h%—%Ç%÷&'&W&‡&·&è''I'z'«'Ü(
(?(q(¢(Ô))8)k)�)Ð**5*h*›*Ï++6+i+�+Ñ,,9,n,¢,×- -A-v-«-á..L.‚.·.î/$/Z/‘/Ç/þ050l0¤0Û11J1‚1º1ò2*2c2
›2Ô3
3F33¸3ñ4+4e4ž4Ø55M5‡5Â5ý676r6®6é7$7`7œ7×88P8Œ8È 99B99¼9ù:6:t:²:ï;-;k;ª;è<'<e<¤<ã="=a=¡=à> >`> >à
?!?a?¢?â@#@d@¦@çA)AjA¬AîB0BrBµB÷C:C}CÀDDGDŠDÎEEU EšEÞF"FgF«FðG5G{GÀHHKH‘H×IIcI©IðJ7J}JÄK KSKšKâL*LrL
ºMMJM“MÜN%NnN·O�OIO“OÝP'PqP»QQPQ›QæR1R|RÇSS_SªS öTBT�TÛU(UuUÂVV\V©V÷WDW’WàX/X}XËYYiY¸ZZVZ¦Zõ[E[
•[å\5\†\Ö]']x]É^^l^½__a_³``W`ª`üaOa¢aõbIbœbðcCc—cëd@d”dée=e’e çf=f’fèg=g“géh?h–hìiCišiñjHjŸj÷kOk§k
ÿlWl¯mm`m¹nnknÄooxoÑp+p†pàq:q•qðrKr¦ss]s¸ttptÌu(u…uáv>v›vøwVw³xxnxÌy*y‰yçzFz¥{{c{Â|!|� |á}A}¡~
~b~Â#„å€G€¨�
�k�Í‚0‚’‚ôƒWƒº„„€„ã…G…«††r†×‡;‡ŸˆˆiˆÎ‰3‰™‰þŠdŠÊ ‹0‹–‹üŒcŒÊ�1�˜�ÿŽfŽÎ�6�ž��n�Ö‘?‘¨’’z’ã“M“¶” ”Š”ô
•_•É–4–Ÿ—
—u—à˜L˜¸™$™�™üšhšÕ›B›¯œœ‰œ÷�d�Òž@ž®ŸŸ‹Ÿú i Ø¡G¡¶¢&¢–££v£æ¤V¤Ç¥8¥©¦¦‹¦ý§n§à¨R¨Ä©7©©ªª�««u« é¬\¬Ð
*D*¸®-®¡¯¯‹°�°u°ê±`±Ö²K²Â³8³®´%´œµµŠ¶¶y¶ð·h·à¸Y¸Ñ¹J¹Â º;ºµ».»§¼!¼›½½�¾
¾„¾ÿ¿z¿õÀpÀìÁgÁãÂ_ÂÛÃXÃÔÄQÄÎÅKÅÈÆFÆÃÇAÇ¿È=ȼÉ:ɹÊ8 Ê·Ë6˶Ì5̵Í5͵Î6ζÏ7ϸÐ9кÑ<ѾÒ?ÒÁÓDÓÆÔIÔËÕNÕÑÖUÖØ
×\×àØdØèÙlÙñÚvÚûÛ€ÜÜŠÝÝ–ÞÞ¢ß)߯à6à½áDáÌâSâÛãcãë äsäü儿
æ–çç©è2è¼éFéÐê[êåëpëûì†ííœî(î´ï@ïÌðXðåñrñÿòŒóó§ô4ôÂõPõÞömöû÷Šø ø¨ù8ùÇúWúçûwüü˜ý)ýºþKþÜÿmÿÿÿáLhttp
://ns.adobe.com/xap/1.0/�<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.5-c002 1.148022, 2012/07/15-18:06:45
">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:xmpRights="http://ns.adobe.com/xap/1.0/rights/"
xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"
xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#"
xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#"
xmlns:xmp="http://ns.adobe.com/xap/1.0/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmpRights:Marked="False"
xmpMM:OriginalDocumentID="xmp.did:a225f730-4f81-4002-af9a-a595e5dccc17"
xmpMM:DocumentID="xmp.did:30709a15-6793-4f65-b425-fb36cadc9bb4"
xmpMM:InstanceID="xmp.iid:30709a15-6793-4f65-b425-fb36cadc9bb4"
xmp:CreatorTool="Adobe Photoshop Lightroom 5.7 (Macintosh)"
xmp:CreateDate="2015-08-28T10:01:04-07:00"
xmp:ModifyDate="2015-09-10T20:56:08-07:00"
xmp:MetadataDate="2015-09-10T20:56:08-07:00"
dc:format="image/jpeg">
<xmpMM:DerivedFrom
stRef:instanceID="xmp.iid:bcfc770f-2378-4e16-830f-1b12d73e3bd5"
stRef:documentID="xmp.did:bcfc770f-2378-4e16-830f-1b12d73e3bd5"
stRef:originalDocumentID="xmp.did:a225f730-4f81-4002-af9a-a595e5dccc17"/>
<xmpMM:History>
<rdf:Seq>
<rdf:li
stEvt:action="saved"


... Los datos de la solicitud superan el tamaño límite de Firebug. ...




E•ÆFe÷¹}D@DDD@DDÿÖï舀ˆˆˆ€¾/¨ƒæ‰¢úˆ)Ñ6ª‘;Y|ØÊ´AFÖMŒ«Dö2rÙ\D¹lœ¶W4M[å²rÛÜ®hš µÊorr›Ü®è¾è‚Ç%½É
ÉeEóDy"¾r[ܯè¾èƒ�Þåó�Þå“¢hƒ�>ää¹dè¾hƒÍÅ<Ü}Ë'DÑ7›�¹<Ü}Ë' DÑ7›�¹}ä¹dhš ±ÈrrÜ¯èš ³ÉrrE^Ñ4Ak’
>äå2½¢h‚×)½ÉËorºˆ-rÛܾòÙ\Dö7¹}å²*Q±“c{•h‚�‹îÖU"
v¦ÕR §F_t_QÍEõ|_Q ÍEõS¢mU"
v¯›YVˆ(Úɱ•h‚ÞÆMŒ®" \¶N[+º&ˆ-rÛÜœ¶W4_PZå7¹|å7¹]Ñ4Ak”Þäå2»¢û¢ ‘÷/œ–Wô_tA�Èrrܯè¾èƒ�+ç VF‰¢ ~@û—Ï7
rÉÑ4A�æãî_|Ü}Ë#DÑ7 }Ëï }Ë#DÑŽHû“’>åDÑžK{—ÞK{•íDyMîNS{•ÝÝZå2rÙ]Ñ4Ao–ɱ•ÄAoc/»Vˆ(Ø›YVˆ)ÚɵTˆ
)Úš*‘Í4_QÍEõ|_Qÿ×ï舀ˆˆˆ€ˆˆˆ€ ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€
ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€
ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ ˆˆˆ€ˆˆˆ€ˆˆ?ÿÐï舀ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆ
ˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆ ˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆ
ˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆ ˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ?ÿÑï舀ˆˆ
ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ
ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ
ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ?ÿÒï舀ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ
ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ
ˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆˆ€ˆˆ? ÿÙ
-----------------------------298031368414422--
Esto mismo lo recupero en el servidor pero todo lo que he intentado para guardar la imagen en disco me ha dado como resultado un archivo de imagen dañado.


Este es uno de los códigos que he hecho para esto.

Código:
ByteArrayDataSource ds = new ByteArrayDataSource (request, "multipart/form-data");
					MimeMultipart multipart = new MimeMultipart(ds);
					for (int i = 0; i < multipart.getCount(); i++) {
						BodyPart bodyPart = multipart.getBodyPart(i);

						System.out.println("body1 : " + bodyPart.getFileName());
						System.out.println("body2 : " + bodyPart.getContentType());

						DataHandler handler = bodyPart.getDataHandler();
						System.out.println("handler : " + handler.getName());
						System.out.println("handler : " + handler.getContentType());

						String curContentType = handler.getContentType();

						if (curContentType.equalsIgnoreCase("application/json")) {
							ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
							handler.writeTo(arrayOutputStream);
							System.out.println("projectsJson : " + arrayOutputStream);
						} else {
							OutputStream outputStream = null;
							String ext = "";
							if (curContentType.equalsIgnoreCase("image/gif")) {
								ext = ".gif";
							} else if (curContentType.equalsIgnoreCase("image/jpeg")) {
								ext = ".jpg";
							}else if (curContentType.equalsIgnoreCase("image/png")) {
								ext = ".png";
							} else if (curContentType.equalsIgnoreCase("image/bmp")) {
								ext = ".bmp";
							} else if (curContentType.equalsIgnoreCase("application/pdf")
									|| (curContentType.equalsIgnoreCase("application/x-pdf"))) {
								ext = ".pdf";
							}

							outputStream = new FileOutputStream("/data/maquina/" + handler.getName() + ext);
							handler.writeTo(outputStream);
							outputStream.flush();
							outputStream.close();
						}


He visto que otros plugins pasan las imágenes o ficheros con el mimos formato, me parece que lo que se envía en el post es unicode pero las conversiones que he hecho no han funcionado.

Necesito su ayuda.

Espero su respuesta.

Un saludo.
  #2 (permalink)  
Antiguo 10/08/2016, 05:27
 
Fecha de Ingreso: marzo-2008
Mensajes: 94
Antigüedad: 18 años, 6 meses
Puntos: 3
Respuesta: Guardar imagen recibida dropzone

Hola a todos!!

Nada como hacer que no te importa para probar de nuevo al día siguiente y que te funcione.

El código de arriba lo he desechado, el problema estaba en que al pasar toda la String que contenida la imagen (sin cabeceras) a una array de bytes, java lo hace a su manera cambiando algunos caracteres, entiendo que es por la diferencia de formatos.

Lo he solucionado creando un método al que le paso el contenido de la imagen (sin cabeceras) en el cual paso el contenido de la imagen byte a byte a una array de bytes que después devuelvo y con la que creo el nuevo archivo de imagen.

Os dejo el código.

request es un String con el contenido que llega de dropzone.

Código:
String nombre = null;

					try {

						Log.d(TAG, "Archivo upload recibido");

						String archivo = null;
						int inicio = 0;
						int fin = 0;

						/*Determinmos el inicio del contenido del archivo*/
						if (request.indexOf("image/gif") != -1) {

							inicio = request.indexOf("image/gif") + 13;
							archivo = request.substring(inicio);

							/*Obtenemos el inicio y final del nombre del archivo*/
							inicio = request.indexOf("filename=") + 10;
							fin = request.indexOf(".gif\"") + 4;

						} else if (request.indexOf("image/jpeg") != -1) {

							inicio = request.indexOf("image/jpeg") + 14;
							archivo = request.substring(inicio);

							/*Obtenemos el inicio y final del nombre del archivo*/
							inicio = request.indexOf("filename=") + 10;
							fin = request.indexOf(".jpg\"") + 4;

						} else if (request.indexOf("image/png") != -1) {

							inicio = request.indexOf("image/png") + 13;
							archivo = request.substring(inicio);

							/*Obtenemos el inicio y final del nombre del archivo*/
							inicio = request.indexOf("filename=") + 10;
							fin = request.indexOf(".png\"") + 4;

						} else if (request.indexOf("image/bmp") != -1) {

							inicio = request.indexOf("image/bmp") + 13;
							archivo = request.substring(inicio);

							/*Obtenemos el inicio y final del nombre del archivo*/
							inicio = request.indexOf("filename=") + 10;
							fin = request.indexOf(".bmp\"") + 4;

						} else if (request.indexOf("application/pdf") != -1) {

							inicio = request.indexOf("image/pdf") + 13;
							archivo = request.substring(inicio);

							/*Obtenemos el inicio y final del nombre del archivo*/
							inicio = request.indexOf("filename=") + 10;
							fin = request.indexOf(".pdf\"") + 4;
						}

						/*Obtenemos el nombre del archivo*/
						nombre = request.substring(inicio, fin);

						Log.d(TAG, "Nombre del archivo " + nombre);

						/*Determinmos el final del contenido del archivo*/
						fin = archivo.indexOf("\r\n--------------");
						archivo = archivo.substring(0, fin);

						/*Creamos el nuevo archico con ruta, nombre y extensión*/
						FileOutputStream fos=new FileOutputStream("/data/maquina/" + nombre);

						/*Utilizamos el metodo string_to_byte para recuperar el contenido del archivo con
						* los valores exactos.
						*
						* Igualamos el array de datos al resultado del metodo*/
						byte[] codigos=string_to_bytes(archivo);

						Log.d(TAG, "Tamaño del archivo " + codigos.length + " bytes");

						/*Escribimos el array de datos en el nuevo archovo*/
						fos.write(codigos);

						/*Cerramos el nuevo archivo*/
						fos.close();

						Log.d(TAG, "Archivo " + nombre + " guardado correctamente");

						return "200/"+nombre+"/successful";
					}catch (Exception e){
						return "204/"+nombre+"/successful";
					}
Y este es el método string_to_bytes

Código:
static byte[] string_to_bytes(String cadena)
	{
		int i;
		int tam=cadena.length();
		byte[] octetos = new byte[tam];
		for (i=0; i<tam; ++i) octetos[i] = (byte) cadena.charAt(i);
		return octetos;
	}
Seguro que hay aun solución mas brillante, así que tenéis este post para indicarla.

Un saludo a todos!!

Etiquetas: files, jquery, 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 12:30.