dqudtskm49788 2011-10-30 06:34
浏览 105
已采纳

尝试从android上传文件时出错

I am trying to upload a file from the simulator to a php server. While there is nothing wrong in logcat or http error log, I don't see the file where it is supposed to be. The server responds with HTTP_OK. Here is the upload function

public void uploadPic() {
    ThreadPolicy tp = ThreadPolicy.LAX;
    StrictMode.setThreadPolicy(tp);

    Log.e("@@@@@@@@@", "Uploadpic called");
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = "/data/icon.jpg";
    String urlServer = "http://192.168.1.9/savepic2.php";
    //String urlServer = "http://winlab.rutgers.edu/~achanda";
    String lineEnd = "
";
    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="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );

    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    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)
    //serverResponseCode = connection.getResponseCode();
    Log.e("@@@@@@@", connection.getResponseMessage());

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

}

Here is the PHP code

    <?php
if ($_FILES["file"]["error"] > 0)
{
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file"]["tmp_name"]. "<br />";

        $target_path = "uploads/";

        $target_path = $target_path . basename( $_FILES["file"]["name"]);

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

What else can go wrong here?

  • 写回答

1条回答 默认 最新

  • duanlin1933 2011-10-30 08:26
    关注

    After some testing I believe your problem is ether todo with permissions within the manifest or the file dont exist on the emulator or device...

    I got the following code to upload to my test server, I used a toast to output the error & a textview to show the result on success.

    Manifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.test.upload"
          android:versionCode="1"
          android:versionName="1.0">
        <uses-sdk android:minSdkVersion="8" />
        <uses-permission android:name="android.permission.INTERNET"></uses-permission>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".AndroidUploadActivity"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
        </application>
    </manifest>
    

    AndroidUploadActivity.class

    package com.test.upload;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class AndroidUploadActivity extends Activity {
        /** Called when the activity is first created. */
        TextView textView1;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            textView1 = (TextView) findViewById(R.id.textView1);
            try {
                upload();
            } catch (Exception e) {
                Toast toast = Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);  
                toast.show();  
                e.printStackTrace();
            }
        }
    
        public void upload() throws Exception {
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
    
            String pathToOurFile = "/sdcard/DCIM/test.png";
            String urlServer = "http://192.168.2.1/androidupload/index.php";
            String lineEnd = "
    ";
            String twoHyphens = "--";
            String boundary = "*****";
    
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
    
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                URL url = new URL(urlServer);
    
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
    
                outputStream = new DataOutputStream(connection.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream
                        .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                                + pathToOurFile + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);
    
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
    
                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);
    
                String serverResponseMessage = connection.getResponseMessage();
    
                textView1.setText(serverResponseMessage);
    
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
        }
    }
    

    main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content"></TextView>
    </LinearLayout>
    

    PHP (Note this is very insecure):

    <?php
    $target_path  = "./";
    
    $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!";
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False