栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

一.manifest文件添加权限
    package="com.android.xxx"
    android:usesCleartextTraffic="true">
   
            android:networkSecurityConfig="@xml/network_security_config"
       
           
               

               
           
       
   

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



    

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

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 = "rn";
        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;
    }
});

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/736568.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号