使用 php 上传文件:$_POST['filename'] 有问题

File uploading with php: problem with $_POST['filename']

我想将文件从我的 Android 应用程序上传到我的 php 服务器(通过 https 上传 URL)

这是我的 php 代码:

$path = "../uploads";
        
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

 $filePath = $path."/".$_POST['filename'];

move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $filePath)

$_FILES['uploaded_file']的内容是:

{"name":"scan.gltf","type":"","tmp_name":"\/srv\/data\/tmp\/phpmEM42e","error":0,"size":5071}

所以当我得到我的文件的名称和正确的大小时,一切似乎都正常。

但是当我登录 $_POST['filename'] 时,我得到一个空字符串。

这怎么可能?如何解决问题?


下面是我的 Android 应用程序中的 Java 代码,但我认为问题不在于此(也许我错了..):

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();

请使用$_FILES代替$_POST

如果您上传文件,您永远不会得到 $_POST 响应,只有 $_FILES 包含您正在搜索的变量。