Ho cercato tutto questo e niente ha funzionato per me.Carica immagine da Android a servlet java e salvalo
Sto provando a caricare un'immagine dall'app per android al servlet Java e salvarla nel server. Ogni soluzione che ho trovato non ha funzionato per me.
Ciò che il mio codice attualmente fa: l'applicazione Android sta inviando l'immagine al servlet, quando sto cercando di salvarla viene creato il file, ma è vuota :(
Grazie per il vostro aiuto
il mio codice nel client Android (i_file è la posizione del file sul dispositivo):
public static void uploadPictureToServer(String i_file) throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://192.168.1.106:8084/Android_Server/GetPictureFromClient");
File file = new File(i_file);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
mio codice lato server:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
InputStream in = request.getInputStream();
OutputStream out = new FileOutputStream("C:\\myfile.jpg");
IOUtils.copy(in, out); //The function is below
out.flush();
out.close();
}
codice IOUtils.copy:
public static long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
Questo non riguarda solo il client, è necessario implementarlo anche sul server (servlet). Btw: cosa fa 'processRequest'? – home
Grazie per la risposta. Ho letto le informazioni nel link, ma non riesco a capire la soluzione per il mio problema. – Ohadza
Come appare il codice del tuo servlet? Cosa succede in 'processRequest'? – home