欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

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

时间:2023-06-12

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

               
           
       
   

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

<?xml version="1.0" encoding="utf-8"?>

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

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

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。