Salve a tutti, da giorni mi sto scontrando con questo problema.
Devo creare un app android che quando aperta invia una semplice immagine al mio server.
Ho consultato decine di codici su google ma nessuno di questi funziona, nel senso che pur non dando errori e senza crashare l'immagine non viene mai effettivamente uploadata sul server.
Comincio a pensare che quindi il problema sia io e non i codici stessi.
Il codice a cui faccio particolare riferimento l'ho trovato su StackOverflow ed è stato postato dall'utente Keaton:
codice:
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http :// mywebsite.com/directory/upload . php";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
Per quanto riguarda invece la parte server:
codice:
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
- Non utilizzando una sd card ho inserito il mio file immagine nella root del telefono (almeno credo... l'ho messo nella prima cartella dopo aver aperto :Phone).
- Al posto di "http : //xyzk/ upload . php" in xyzk ho provato sia ad inserire l'indirizzo del gateway(essendo connesso alla rete del server) sia ad inserire l'ip pubblico della rete (connettendomi alla rete 4G).
- il server è ovviamente attivo e credo di avere già tutti i permessi (ho effettuato altre operazioni da pc, nel caso sapreste indicarmi come posso vedere se ho i permessi?)
- ho creare directory e cartelle con i nomi giusti.
- ho avviato l'app sia mantenendo il terminale connesso ad eclipse, sia scollegato dal pc.
Il risultato ottenuto è sempre lo stesso: Schermata bianca (tutto ok, non ci sono elementi grafici) ma file che non viene MAI caricato sul server.
La mainActivity contiene solo la chiamata alla funzione che ho copiato su.
Sono disperato... non so più a che santo votarmi. Grazie a tutti anticipatamente e scusate la lunghezza del post.