从Android上传Php图片

时间:2015-01-27 16:03:54

标签: php android image upload

我在我的代码中遇到了这个问题。我试图通过php将我的SD卡上的图像上传到我的服务器。 这是Android中的功能:

public int uploadToServer(String which, String sourceFileUri) throws IOException{
      final String upLoadServerUri = "http://www.mywebsite.com/my_page.php";
        HttpURLConnection conn;
        DataOutputStream dos;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
        int serverResponseCode = 0;

        if (!sourceFile.isFile()) {
            Log.e("uploadFile", "Source File not exist : " + sourceFileUri);

            return 0;
        } else {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP  connection to  the URL
                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");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", sourceFileUri);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + sourceFileUri + "\"" + sourceFileUri);                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);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {
                    // Read response
                    StringBuilder responseSB = new StringBuilder();
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    String line;
                    while ( (line = br.readLine()) != null)
                         responseSB.append(line);

                    // Close streams
                    br.close();


                            Log.i("uploadFile", "Path is : " + sourceFileUri);
                            Log.i("Output", responseSB.toString());

                }

                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                ex.printStackTrace();

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                e.printStackTrace();

                Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
            }
            return serverResponseCode;

        }
}

这是我的PHP代码

<?php


echo "<pre>";
var_dump($_FILES);
echo "</pre>";



    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }


 ?>

这是我得到的答案:

I/uploadFile(15262): HTTP Response is : OK: 200
I/uploadFile(15262): Path is : /mnt/sdcard/Prova2.png
I/Output(15262): <pre>array(1) {  ["uploaded_file"]=>  array(5) {    ["name"]=>    string(15) "Prova2.png?PNG"    ["type"]=>    string(0) ""    ["tmp_name"]=>    string(14) "/tmp/phpu9Qkwu"    ["error"]=>    int(0)    ["size"]=>    int(693)  }}</pre> success

我不明白为什么会得到&#34; Prova2.png?PNG&#34;而不是&#34; Prova2.png&#34;,我认为错误存在,但我不确定。

提前谢谢

0 个答案:

没有答案