无法通过PHP(Android)上传名称中有空格的文件


Cannot upload file with space in name via PHP (Android)

我使用以下Android/PHP代码将文件上传到服务器。除非原始文件名中有空格,否则所有文件都能正常工作,此时它将失败。

安卓系统:(有问题的空间在字符串路径变量中)

public static void uploadFile(String path,String group,String folder) {

        HttpURLConnection conn = null;

            String lineEnd = "'r'n";
            String twoHyphens = "--";
            String boundary = "*****";
            try {
                // ------------------ CLIENT REQUEST

                FileInputStream fileInputStream = new FileInputStream(new File(
                        path));


                // open a URL connection to the Servlet
                URL url = new URL("http://uploadsite.php" +
                        "?group_name=" + group + "&folder=" + folder  );
                // 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);

             DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                                + path + "" + lineEnd);
                dos.writeBytes(lineEnd);
                // create a buffer of maximum size

                int bytesAvailable = fileInputStream.available();
                int maxBufferSize = 1*1024*1024;
                byte[] buffer = new byte[bytesAvailable];
                // read file and write it into form...
                int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
                while (bytesRead > 0) {
                    dos.write(buffer, 0, bytesAvailable);
                    bytesAvailable = fileInputStream.available();
                    bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                // close streams
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                Log.e(TAG, "error: " + ex.getMessage(), ex);
            }
            catch (IOException ioe) {
                Log.e(TAG, "error: " + ioe.getMessage(), ioe);
            }
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    Log.e(TAG, "Message: " + line);
                }
                rd.close();
            } catch (IOException ioex) {
                Log.e(TAG, "error: " + ioex.getMessage(), ioex);
            }
            return;
}

PHP:

<?php
 $group = $_GET["group_name"];
 $folder = $_GET["folder"];
 $base_path  = "./db/";
 $path = $base_path . $group;

$target_path = $path . "/" . $folder . "/" . basename( $_FILES['uploadedfile']['name']);
$group = ( $_FILES['group_name']['name']);

$file = 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 ($path.basename( $_FILES['uploadedfile']['name']), 0777);
} else{
    echo "There was an error uploading the file, please try again!(".basename( $_FILES['uploadedfile']['name']).")";
}
?>

关于如何在不更改android端文件名的情况下上传此文件,有什么建议吗?

谢谢Josh

一些字符在URL中使用时具有特殊意义。这就是为什么你总是必须正确地编码你的字符串成为url的一部分。使用Java,您可以使用URLEncoder类来完成这项工作。所以你的

dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                            + path + "" + lineEnd);

应该看

dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                            + URLEncoder.encode(path, "UTF-8") + lineEnd);

编辑

如果您需要将字符串解码回其原始形式,那么在PHP方面,您可以使用urldecode()

您应该对包含空格或特殊符号等的url进行编码。。

使用进行编码

     URLEncoder.encode("your url here");

供您的代码使用:

    URL url = new URL("http://uploadsite.php" +
                    "?group_name=" + URLEncoder.encode(group) + "&folder=" + URLEncoder.encode(folder)  );

有关更多信息,请访问此问题可能会帮助您:Android 中的URL编码