Ciao,
sto cercando di caricare un file immagine da app android (sviluppata con android studio) e ho un problema il codice java rileva il corretto caricamento ma del file non c'è traccia sul server.
Sul mio spazio altervista ho sviluppato il codice php per leggere il file attraverso la variabile $_FILE.
Nel codice php ho aggiunto delle insert ad una mia tabella di log. Ho così scoperto che il php viene correttamente richiamato dalla app ma la variabile $_FILE è sempre vuota . dai log della parte java risulta che scrivo tutti i byte con la write dell'outputstream.
C'è qualche impostazione da fare sul server o qualcuno riesce a suggerirmi cosa sto sbagliando ?
Di seguito il codice php e la parte java di connessione e scrittura stream.
Grazie mille per l'aiuto !
Ciao
Codice PHP:
<?php
$DBhost = "locale";
$DBuser = "uuuuuuu";
$DBpass = "xxxxxxx";
$DBName = "yyyyyyy";
$connect = mysqli_connect($DBhost, $DBuser, $DBpass, $DBName);
$modulo="caricafoto";
$azione="input";
$dataq = date('Y/m/d');
$ora = date('H:i:s');
$input = $_FILES["uploaded_file"]["name"]." - ".$_FILES["uploaded_file"]["error"];
$sqlx = $_FILES["uploaded_file"]["size"];
$querylog = "INSERT INTO `Log`(`data`, `ora`, `modulo`, `azione`, `query`, `dati`) VALUES ('".$dataq."','".$ora."','".$modulo."','".$azione."','".$sqlx."','".$input."')";
mysqli_query($connect, $querylog);
$target_dir = "account/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
echo "nome file di arrivo : ".$target_file."<br>" ;
$msg2 = "nome file di arrivo : ".$target_file."<br>" ;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// verifichiamo che il file è stato caricato
if(!is_uploaded_file($_FILES["fileToUpload"]["tmp_name"]) or $_FILES["fileToUpload"]["error"]>0) {
echo "Si sono verificati problemi nella procedura di upload! " .$_FILES["fileToUpload"]["error"]."<br>";
$msg = "Si sono verificati problemi nella procedura di upload! " .$_FILES["fileToUpload"]["error"]."<br>";
$uploadOk = 0;
}
else {
// Check if image file is a actual image or fake image
//if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".<br>";
$uploadOk = 1;
} else {
echo "File is not an image.";
$msg = "File is not an image - " . $check["mime"] . ".<br>";
$uploadOk = 0;
}
//}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$msg = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$msg = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
$modulo="caricafoto";
$azione="output";
$dataq = date('Y/m/d');
$ora = date('H:i:s');
$input = $msg;
$sqlx = " ";
$querylog = "INSERT INTO `Log`(`data`, `ora`, `modulo`, `azione`, `query`, `dati`) VALUES ('".$dataq."','".$ora."','".$modulo."','".$azione."','".$sqlx."','".$input."')";
mysqli_query($connect, $querylog);
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Codice:
public int uploadFile(final String selectedFilePath){
String urlbase = "http://asgardproduction.altervista.org/moduliphp/uploadfoto.php";
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 4096;
Log.v("uploadfoto"," file da trasferire " + selectedFilePath);
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
Toast.makeText(c,"Errore in caricamento foto : file non trovato "+selectedFilePath,Toast.LENGTH_SHORT).show();
return serverResponseCode;
}else{
try{
Uri imgUri = Uri.parse(String.valueOf(Uri.fromFile(selectedFile)));
Log.v("uploadfoto"," tradotto il file in URI : " + imgUri);
InputStream inputStream = c.getContentResolver().openInputStream(imgUri);
//FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(urlbase);
connection = (HttpURLConnection) url.openConnection();
Log.v("uploadfoto"," eseguito il connect a " + connection);
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//returns no. of bytes present in fileInputStream
bytesAvailable = inputStream.available();
Log.v("uploadfoto","inizio della lettura " + bytesAvailable);
//bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = inputStream.read(buffer,0,bufferSize);
Log.v("uploadfoto","byte letti " + buffer+ " - "+bufferSize);
//bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
Log.v("uploadfoto","scrivo una stringa di byte dal buffer " + buffer+ " - "+bufferSize);
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = inputStream.available();
//bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = inputStream.read(buffer,0,bufferSize);
//bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
Log.v("uploadfoto","fine della scrittura " + String.valueOf(bytesAvailable));
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.v("uploadfoto", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
Log.v("uploadfoto", "foto caricata correttamente " + foto);
}
//closing the input and output streams
inputStream.close();
//fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
Log.v("uploadfoto"," errore ioexception " + e );
e.printStackTrace();
} catch (MalformedURLException e) {
Log.v("uploadfoto"," errore ioexception " + e );
e.printStackTrace();
} catch (IOException e) {
Log.v("uploadfoto"," errore ioexception " + e );
e.printStackTrace();
}
}
return serverResponseCode;
}