Android上传文件用php接收

废话不多说直接上代码

导包

    implementation 'com.loopj.android:android-async-http:1.4.11'

http声明

 

<application
        android:usesCleartextTraffic="true"

 

函数

public void uploadFile() throws FileNotFoundException {

        AsyncHttpClient client=new AsyncHttpClient();
        RequestParams params=new RequestParams();
        String filePath="/data/data/com.example.android_uploadfile/cache/cxk.jpg";
        params.put("data",new File(filePath));
        client.post(this, "http://XXX.com/XXX.php", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody) {
                System.out.println(new String(responseBody));
            }
            @Override
            public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
                System.out.println(new String(responseBody));
            }
        });
    }

修改上面代码中加粗的部分

php代码

<?php
header("Content-Type: text/html;charset=utf-8");
$fileInfo=$_FILES['data'];//获取提交过来的文件
$filename=$fileInfo['name'];//获取文件名
$filePath=$fileInfo['tmp_name'];//获取文件临时目录
$name = iconv('utf-8', 'gb2312', $filename);//把文件名重新编码,避免吗中文乱码
move_uploaded_file($filePath,"./".$name);
echo($filename);

Github地址 下载前给star

 

posted @ 2022-11-12 10:54  Z_Chan  阅读(87)  评论(0编辑  收藏  举报