I want to upload files from my Android app to my php server (through a https upload URL)
Here is my php code :
$path = "../uploads"; if (!file_exists($path)) { mkdir($path, 0777, true); } $filePath = $path."/".$_POST['filename']; move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $filePath)
The content of $_FILES['uploaded_file']
is:
{"name":"scan.gltf","type":"","tmp_name":"/srv/data/tmp/phpmEM42e","error":0,"size":5071}
So everything seems ok as I get the name of my file and its correct size.
But when I log $_POST['filename']
, I get a null string.
How is that possible ? How to solve the problem ?
Here below my Java code from my Android app but I don’t think that the problem comes from there (perhaps I am wrong..):
FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(urlString); // Open a HTTP connection to the URL // TODO HttpURLConnection or HttpsURLConnection ??? conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); // TODO Space or no space before 'boundary=' ? conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileUrl); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); // TODO Space or no space before 'filename=' ? dos.writeBytes("Content-Disposition: form-data; name="uploaded_file"; filename="" + fileUrl + """ + 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 necessary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage();
Advertisement
Answer
Please use $_FILES
instead of $_POST
if you upload a file, you never get a $_POST
response, only $_FILES
hold the variables you are searching for.