android向服务器传输文件并获取文件url

一.manifest文件添加权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.xxx"
    android:usesCleartextTraffic="true">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        <activity android:name=".activities.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

在res中新建xml目录并新建network_security_config.xml文件,文件内容如下

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

二. 定义接口返回传输结果

public interface IBvImageSelectCallback {

    void OnUploadSuccess(String data);

    Void OnUploadFail();
}

三.上传方法

string URL_POST_IMAGE = "http://xxxx";//地址

private static final String CHARSET = "UTF-8"; // 设置编码
private static final ExecutorService threadPool = Executors.newSingleThreadExecutor();

public static void doPostFeedbackUpload( final File file, IBvImageSelectCallback callback) {

        String boundary = UUID.randomUUID().toString(); // 边界标识 随机生成
        String prefix = "--";
        String line_end = "\r\n";
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(URL_POST_IMAGE);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                    conn.setConnectTimeout(TIME_OUT);
                    conn.setDoInput(true); // 允许输入流
                    conn.setDoOutput(true); // 允许输出流
                    conn.setUseCaches(false); // 不允许使用缓存
                    conn.setRequestMethod("POST"); // 请求方式
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
                    Log.d(TAG, "doPostFeedbackImage: file = " + file);
                    if (file != null) {
                        DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
                        StringBuffer stringBuffer = new StringBuffer();
                        stringBuffer.append(prefix);
                        stringBuffer.append(boundary);
                        stringBuffer.append(line_end);
                        stringBuffer.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
                                + file.getName() + "\"" + line_end);
                        stringBuffer.append("Content-Type: application/octet-stream; charset=" + CHARSET + line_end);
                        stringBuffer.append(line_end);
                        dataOutputStream.write(stringBuffer.toString().getBytes());
                        FileInputStream inputStream = new FileInputStream(file);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while ((len = inputStream.read(bytes)) != -1) {
                            dataOutputStream.write(bytes, 0, len);
                        }
                        inputStream.close();
                        dataOutputStream.write(line_end.getBytes());
                        byte[] end_data = (prefix + boundary + prefix + line_end).getBytes();
                        dataOutputStream.write(end_data);
                        dataOutputStream.flush();
                        dataOutputStream.close();
                        int res = conn.getResponseCode();
                        Log.e(TAG, "response code:" + res);
                         if(res==200)
                         {
                             String responseString = "";
                             InputStream inputStream1= conn.getInputStream();
                             responseString =                        readInputStreamToString(inputStream1);//服务器返回的内容
                             conn.disconnect();
                             if(callback != null) {
                                 callback.OnUploadSuccess(responseString);
                             }
                         } else {
                             conn.disconnect();
                             if (callback != null) {
                                 callback.OnUploadFail();
                             }
                         }
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }


    private static String readInputStreamToString(InputStream is) {
        byte[] result;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            baos.close();
            result = baos.toByteArray();
        } catch (IOException e) {
            Log.e(TAG, "readInputStreamToString error. message: " + e.getMessage());
            return "error";
        }
        return new String(result);
    }

四.调用

File file = new File(filepath);
NetworkUtil.doPostFeedbackUpload( file, new IBvImageSelectCallback() {
    @Override
    public void OnUploadSuccess(String data) {
//do something
    }

    @Override
    public Void OnUploadFail() {
        return null;
    }
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值