1

Android コードから PHP Web サーバー コードにビデオをアップロードしようとしていますが、成功しません。次のリンクを参照してアップロード タスクを実行していますが、Android コードで次の応答を得ていますが、PHP サーバーにファイルが見つかりません。

Android の応答

DEBUG/ServerCode(29484): 200
DEBUG/serverResponseMessage(29484): OK

php.iniファイルに値を設定するなど、多くのことを確認しました。Androidコードからサーバーに画像をアップロードできますが、Androidから64ビットエンコードByteArrayを送信しているため、エンコードされたsから画像を作成できるphpの既製の関数がありますByteArray

しかし、そのコードは、画像以外のタイプの他のファイルの場合にも機能しません。

以前に似たようなことをしたことがある方がいらっしゃいましたらご指導ください。

私が使用しているPHPコード:

<?php

    $target_path  = "./upload/";

    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
    {
        echo "The file ".basename( $_FILES['uploadedfile']['name'])." has been uploaded";
    } 
    else
    {
        echo "There was an error uploading the file, please try again!";
    }
?>

私が使用しているAndroidコード:

public void videoUpload()
{
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;


    String pathToOurFile = "/sdcard/video-2010-03-07-15-40-57.3gp";
    String urlServer = "http://10.0.0.15/sampleWeb/handle_upload.php";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary");

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile );
    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    int serverResponseCode = connection.getResponseCode();
     String serverResponseMessage = connection.getResponseMessage();
     Log.d("ServerCode",""+serverResponseCode);
     Log.d("serverResponseMessage",""+serverResponseMessage);
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
4

2 に答える 2

2

私のJavaは少し厄介ですが....

connection.getResponseCode は HTTP ステータス コードのみを返し、connection.getResponseMessage は HTTP ステータス メッセージのみを返しているように見えますが、PHP はこれらの値を操作するために何もしません。あなたは試すことができます:

$target_path  = "./upload/";
$src = $_FILES['uploadedfile']['name'];

$target_path .= basename($src);

if(file_exists($src) 
        && 
        && move_uploaded_file($src, $target_path)
   ) {
    echo "The file ".basename( $_FILES['uploadedfile']['name'])." has been uploaded";
} else {
    header("Server Error", true, 503);
    echo "There was an error uploading the file, please try again!";
    $msg = "src size ? " 
       . filesize($src) . "\n dest dir writable ?"
       . is_writeable(dirname($target_path)) ? "Y\n" : "N\n"
       . "FILES contains :\n";
       . var_export($_FILES,true);
    // now write $msg somwhere you can read it
}

これは、何が悪かったのかを絞り込むのに役立ちます

于 2011-02-09T12:37:38.673 に答える
1
private String mString;
private Uri image_uri;  
private String response;    
private HttpURLConnection conn = null;
private DataOutputStream dos = null;
private String lineEnd = "\r\n";
private String twoHyphens = "--";
private String boundary = "*****";
private int bytesRead, bytesAvailable, bufferSize;
private byte[] buffer;
private String url_for_image_upload = "your_web_api_put_here";
private int maxBufferSize = 1 * 1024 * 1024;

//次に、ボタンの onclick リスナーでこれら 2 つのメソッドを呼び出します

mString = getRealPathFromURI(image_uri);

ImageUpload();

//これらのメソッドをここに記述

private void ImageUpload() {

    Toast.makeText(getApplicationContext(),
            "Please Wait while uploading Image", Toast.LENGTH_SHORT).show();

    try {
        FileInputStream fileInputStream = new FileInputStream(new File(mString));
        URL url = new URL(url_for_image_upload);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);

        conn.setDoOutput(true);

        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"img_name\";filename=\"img_name"
                + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        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);
        }
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        Log.d("BuffrerReader", "" + in);

        if (in != null) {
            response = convertStreamToString(in);
            Log.e("FINAL_RESPONSE-LENGTH",""+response.length());
            Log.e("FINAL_RESPONSE", response);
        }

        fileInputStream.close();
        dos.flush();
        dos.close();

        if (response.startsWith("0")) {
            Toast.makeText(getApplicationContext(),
                    "Image Uploaded not successfully", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Image Uploaded successfully", Toast.LENGTH_SHORT)
                    .show();

        }

    } catch (MalformedURLException ex) {
        Log.e("Image upload", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Image upload", "error: " + ioe.getMessage(), ioe);
    }

}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaColumns.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();

    mString = cursor.getString(column_index);

    return mString;

}

public static String convertStreamToString(BufferedReader is)
        throws IOException {
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {

            while ((line = is.readLine()) != null) {
                sb.append(line).append("");
            }
        } finally {
            is.close();
        }
        return sb.toString();
    } else {
        return "";
    }
}
于 2013-04-11T06:39:20.673 に答える