通过PHP将文件从Android上传到服务器 [英] Upload a file from Android to the server via PHP

查看:195
本文介绍了通过PHP将文件从Android上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我使我的代码正常工作吗,例如,通过PHP将Android中的文件上传到服务器上吗?我以许多不同的方式尝试了它,但是它不起作用.我收到HTTP响应200,但文件未上传到服务器上.

Can anyone help me to make my code work, i.e. upload a file from Android to the server via PHP? I tried it in many different ways but it won't work. I get HTTP Response 200 but the files aren't uploaded on server.

我用于上传的PHP脚本是:

The PHP script I'm using for upload is:

<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
?>

我也尝试过使用Httpmime 4.0中的multipart,但无法正常工作.

I also tried using multipart from Httpmime 4.0 but it wont work.

public void uploadFile(String path)
{
    File file = new File(path);
    try {
        HttpClient client = new DefaultHttpClient();
        String postURL = upLoadServerUri;
        HttpPost post = new HttpPost(postURL);
        FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("uploaded_file", bin);
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            Log.i("RESPONSE Wahaj: ","Code : "+ EntityUtils.toString(resEntity));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

推荐答案

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();

    }

}

这是AsyncTask"Helpher"类,用于从Android上传图像.要调用此类,请使用下面的语法.

This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.

new Main2Activity.Helpher(this).execute(fileUri.getPath());

这是fileUri.getPath()本地图像的位置.

Here fileUri.getPath() local image location.

这篇关于通过PHP将文件从Android上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆