Java 无法将文件从Android上载到PHP服务器

Java 无法将文件从Android上载到PHP服务器,java,php,android,Java,Php,Android,我正在制作一个应用程序,将文件从SD卡上传到PHP服务器。然而,当我尝试这样做时,我得到了一个错误 我的Android代码如下: package de.fileupload; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import androi

我正在制作一个应用程序,将文件从
SD
卡上传到
PHP
服务器。然而,当我尝试这样做时,我得到了一个错误

我的Android代码如下:

package de.fileupload;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import android.os.Bundle;

@SuppressWarnings("unused")
public class FileUpload extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final TextView tmp = (TextView) findViewById(R.id.textView1);
    tmp.setText("Hi! Click the button!");

    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    File f = new File("mnt/sdcard/SMSBackup.txt");
    try {
    f.createNewFile();
    Date d = new Date();
    PrintWriter writer = new PrintWriter(f);
    writer.println(d.toString());
    writer.close();
    HttpClient client = new DefaultHttpClient();
    httpPostFileUpload(client, "mnt/sdcard/SMSBackup.txt", "http://10.0.2.2:8080/admin/admin/upload1.php", "uploadedfile");
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    });
    }
    public void httpPostFileUpload(
    HttpClient client,
    String filePath,
    String uploadUri,
    String inputNameAttr) throws ClientProtocolException,
    IOException {
    HttpUriRequest request = new HttpPost(uploadUri);
    MultipartEntity form = new MultipartEntity();

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
    form.addPart(inputNameAttr, new FileBody(new File(filePath)));
    ((HttpEntityEnclosingRequestBase) request).setEntity(form);
    try {
    client.execute(request);
    } catch (ClientProtocolException e) {
    throw e;
    } catch (IOException ee) {
    throw ee;
    }
    }
    }
我的PHP文件如下:

package de.fileupload;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import android.os.Bundle;

@SuppressWarnings("unused")
public class FileUpload extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final TextView tmp = (TextView) findViewById(R.id.textView1);
    tmp.setText("Hi! Click the button!");

    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    File f = new File("mnt/sdcard/SMSBackup.txt");
    try {
    f.createNewFile();
    Date d = new Date();
    PrintWriter writer = new PrintWriter(f);
    writer.println(d.toString());
    writer.close();
    HttpClient client = new DefaultHttpClient();
    httpPostFileUpload(client, "mnt/sdcard/SMSBackup.txt", "http://10.0.2.2:8080/admin/admin/upload1.php", "uploadedfile");
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    });
    }
    public void httpPostFileUpload(
    HttpClient client,
    String filePath,
    String uploadUri,
    String inputNameAttr) throws ClientProtocolException,
    IOException {
    HttpUriRequest request = new HttpPost(uploadUri);
    MultipartEntity form = new MultipartEntity();

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
    form.addPart(inputNameAttr, new FileBody(new File(filePath)));
    ((HttpEntityEnclosingRequestBase) request).setEntity(form);
    try {
    client.execute(request);
    } catch (ClientProtocolException e) {
    throw e;
    } catch (IOException ee) {
    throw ee;
    }
    }
    }
upload1.php

<meta name="generator" content="Namo WebEditor(Trial)">
<form enctype="multipart/form-data" action="upload.php" method="POST"> 
<input type="hidden" name="MAX_FILE_SIZE" value="100000" /> 
 Choose a file to upload: <input name="uploadedfile" type="file" /><br /><input 
 type="submit" value="Upload File" /> 
 </form> 
 <?php 
 $to_file = "tmp/" . basename($_FILES['uploadedfile']['name']); 
 $from_file = $_FILES['uploadedfile']['tmp_name']; 
 if (move_uploaded_file($from_file, $to_file)) { 
  echo "Successful upload"; 
 ?> 
 <a href="<?php echo $to_file;?>"><?php echo $to_file;?></a> 
 <?php 
 } else { 
 echo "Unsuccessful upload"; 
 } 
 ?> 

选择要上载的文件:
upload.php是:

<?php
// Where the file is going to be placed 
$target_path = "localhost/admin/admin/uploads/";

/* Add the original filename to our target path.  
 Result is "uploads/filename.extension" */
 $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";
 chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
 } else{
 echo "There was an error uploading the file, please try again!";
 echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
 echo "target_path: " .$target_path;
 }
 ?>


谁能告诉我哪里错了吗?它始终显示文件的未成功上载。当我的服务器运行时

尝试使用
移动上传的文件()
,函数
复制()
。它们使用相同的输入参数,如下所示:

if(copy($_FILES['uploadedfile']['tmp_name'], $target_path)) { ...
很可能PHP进程没有权限在成功上载后将上载的文件移动到其他文件夹,因为移动实质上包含复制和删除操作

还有一件事-尽量不要将上传文件的权限更改为0644,因为这也可以限制为PHP进程,即当您在Linux上处理文件系统操作时(我假设您的服务器使用Linux机器),工作进程(在您的情况下是PHP和apache)设置了特定权限,可能他们无法将文件删除/移动到工作文件夹之外。
您还应将上传文件夹权限更改为755或777。

尝试使用
移动上传的文件()
,函数
复制()
。它们使用相同的输入参数,如下所示:

if(copy($_FILES['uploadedfile']['tmp_name'], $target_path)) { ...
很可能PHP进程没有权限在成功上载后将上载的文件移动到其他文件夹,因为移动实质上包含复制和删除操作

还有一件事-尽量不要将上传文件的权限更改为0644,因为这也可以限制为PHP进程,即当您在Linux上处理文件系统操作时(我假设您的服务器使用Linux机器),工作进程(在您的情况下是PHP和apache)设置了特定权限,可能他们无法将文件删除/移动到工作文件夹之外。
您还应该将上载文件夹权限更改为755或777。

此类允许您直接上载文件。不需要解码你的文件

public class Helpher extends AsyncTask<String, Void, String> {
    Context context;
    JSONObject json;
    ProgressDialog dialog;
    int serverResponseCode = 0;
    DataOutputStream dos = null;
    FileInputStream fis = null;
    BufferedReader br = null;


    public Helpher(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {

        dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
    }

    @Override
    protected String doInBackground(String... arg0) {

        try {
            File f = new File(arg0[0]);
            URL url = new URL("http://localhost:8888/imageupload.php");
            int bytesRead;
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
                    + f.getName() + "\"";
            String contentType = "Content-Type: application/octet-stream";


            dos = new DataOutputStream(conn.getOutputStream());
            fis = new FileInputStream(f);


            dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
            dos.writeBytes(contentDisposition + NEW_LINE);
            dos.writeBytes(contentType + NEW_LINE);
            dos.writeBytes(NEW_LINE);
            byte[] buffer = new byte[MAX_BUFFER_SIZE];
            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
            }
            dos.writeBytes(NEW_LINE);
            dos.writeBytes(SPACER + BOUNDARY + SPACER);
            dos.flush();

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                Log.w(TAG,
                        responseCode + " Error: " + conn.getResponseMessage());
                return null;
            }

            br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            Log.d(TAG, "Sucessfully uploaded " + f.getName());

        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            try {
                dos.close();
                if (fis != null)
                    fis.close();
                if (br != null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return String.valueOf(serverResponseCode);
    }


    @Override
    protected void onPostExecute(String result) {
        dialog.dismiss();

    }

}

这里是fileUri.getPath()本地图像位置如果希望看到服务器响应值在“StringBuilder sb”中可用,可以打印sb值

此类允许您直接上载文件。不需要解码你的文件

public class Helpher extends AsyncTask<String, Void, String> {
    Context context;
    JSONObject json;
    ProgressDialog dialog;
    int serverResponseCode = 0;
    DataOutputStream dos = null;
    FileInputStream fis = null;
    BufferedReader br = null;


    public Helpher(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {

        dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
    }

    @Override
    protected String doInBackground(String... arg0) {

        try {
            File f = new File(arg0[0]);
            URL url = new URL("http://localhost:8888/imageupload.php");
            int bytesRead;
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
                    + f.getName() + "\"";
            String contentType = "Content-Type: application/octet-stream";


            dos = new DataOutputStream(conn.getOutputStream());
            fis = new FileInputStream(f);


            dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
            dos.writeBytes(contentDisposition + NEW_LINE);
            dos.writeBytes(contentType + NEW_LINE);
            dos.writeBytes(NEW_LINE);
            byte[] buffer = new byte[MAX_BUFFER_SIZE];
            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
            }
            dos.writeBytes(NEW_LINE);
            dos.writeBytes(SPACER + BOUNDARY + SPACER);
            dos.flush();

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                Log.w(TAG,
                        responseCode + " Error: " + conn.getResponseMessage());
                return null;
            }

            br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            Log.d(TAG, "Sucessfully uploaded " + f.getName());

        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            try {
                dos.close();
                if (fis != null)
                    fis.close();
                if (br != null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return String.valueOf(serverResponseCode);
    }


    @Override
    protected void onPostExecute(String result) {
        dialog.dismiss();

    }

}

这里是fileUri.getPath()本地图像位置如果要查看服务器响应值在“StringBuilder sb”中是否可用,可以打印sb值

会出现什么错误?你能发布堆栈跟踪吗?你没有试着把它上传到你的本地主机上,是吗?你用简单的HTML文件上传表单单独测试了PHP文件吗?通过这种方式,您可以很容易地理解问题是在PHP还是Android中,我在upload1.PHP上得到的错误如下:未定义的索引:第7行的D:\wamp\www\admin\admin\upload1.PHP中的uploadedfile,在upload.PHP上得到的错误如下:move_upload_file(localhost/admin/admin/uploads/SMSBackup.txt)[function.move upload file]:无法打开流:第9行的D:\wamp\www\admin\admin\upload.php中没有这样的文件或目录,第9行的D:\wamp\www\admin\admin\upload.php中的move\u upload\u file()[function.move upload file]:无法将“D:\wamp\tmp\php139.tmp”移动到“localhost/admin/admin/uploads/SMSBackup.txt”中。您遇到了什么错误?你能发布堆栈跟踪吗?你没有试着把它上传到你的本地主机上,是吗?你用简单的HTML文件上传表单单独测试了PHP文件吗?通过这种方式,您可以很容易地理解问题是在PHP还是Android中,我在upload1.PHP上得到的错误如下:未定义的索引:第7行的D:\wamp\www\admin\admin\upload1.PHP中的uploadedfile,在upload.PHP上得到的错误如下:move_upload_file(localhost/admin/admin/uploads/SMSBackup.txt)[function.move upload file]:无法打开流:第9行的D:\wamp\www\admin\admin\upload.php中没有这样的文件或目录,第9行的D:\wamp\www\admin\admin\upload.php中的move\u upload\u file()[function.move upload file]:无法将“D:\wamp\tmp\php139.tmp”移动到“localhost/admin/admin/uploads/SMSBackup.txt”。