android中的图片(文件)的上传

来源:互联网 发布:linux修改文件夹命令 编辑:程序博客网 时间:2024/06/05 14:34
  • 第一种方法
  • 写一个上传的类实现上传图片和文件的功能.

参考文件
android中的文件(图片)上传
这种方法需要开线程.
在onCreate方法中调用.

DownloadThread downloadThread = new DownloadThread();downloadThread.start();

开线程.

    class DownloadThread extends Thread{        @Override        public void run() {            try{                System.out.println("开始下载文件");                //文件下载完成后更新UI                String requestURL = "http://...";                String picPath = Environment.getExternalStorageDirectory()+"/xxx.jpg";                File file = new File(picPath);                Log.i("upload", "file exists:" + file.exists());                if (file.exists()) {                    Map<String, String> params = new HashMap<>();//                    参数添加                    params.put("xx", "xx");                    String request = UploadUtil.uploadFile(file, requestURL, params, "xxx");                    Log.i("upload", request);                }                //此处让线程DownloadThread休眠5秒中,模拟文件的耗时过程                Thread.sleep(5000);                System.out.println("文件下载完成");            }catch (InterruptedException e){                e.printStackTrace();            }        }    }
  • 第二种方法
  • 利用Okhttp3网络请求框架实现
    参考文章
    OKhttp3.X 3.0上传图片文件及表单MultipartBody
 private void upFile(){        String requestURL = "http:..";        String picPath = Environment.getExternalStorageDirectory()+"/xx.jpg";        File file = new File(picPath);        Map<String, String> params = new HashMap<>();        MultipartBody.Builder builder=  new MultipartBody.Builder().setType(MultipartBody.FORM);        if(params==null){        //"image/*" 类型            builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/*"),file)            ).build();        }else{        //带参数            for (String key : params.keySet()) {                builder.addFormDataPart(key, params.get(key));            }            builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/*"),file)            );        }    /* 下边的就和post一样了 */        Request request = new Request.Builder().url(requestURL).post(builder.build()).build();        mOkHttpClient.newCall(request).enqueue(new Callback() {            public void onResponse(Call call, Response response) throws IOException {                final  String bodyStr = response.body().string();                final boolean ok = response.isSuccessful();                runOnUiThread(new Runnable() {                    public void run() {                        if(ok){                            Toast.makeText(MainActivity.this, bodyStr, Toast.LENGTH_SHORT).show();                            Log.i("upload++++++++", bodyStr);                        }else{                            Toast.makeText(MainActivity.this, "server error : " + bodyStr, Toast.LENGTH_SHORT).show();                            Log.i("upload+++++++++", bodyStr);                        }                    }                });            }            public void onFailure(Call call, final IOException e) {                runOnUiThread(new Runnable() {                    public void run() {                        Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();                    }                });            }        });    }

在onCreate方法中调用.

  OkHttpClient.Builder builder = new OkHttpClient.Builder();        mOkHttpClient= builder.build();        upFile();

方法一提到的工具类:

public class UploadUtil {    private static final String TAG = "uploadFile";    private static final int TIME_OUT = 10 * 1000; //超时时间    private static final String CHARSET = "utf-8";    private static final String BOUNDARY = UUID.randomUUID().toString(); //边界标识随机生成    private static final String PREFIX = "--";    private static final String LINE_END = "\r\n";    private static final String CONTENT_TYPE = "multipart/form-data"; //内容类型    /**     * Android上传文件到服务端     *     * @param file       需要上传的文件     * @param RequestURL 请求的rul     * @return 返回响应的内容     */    public static String uploadFile(File file, String RequestURL, Map<String, String> params, String uploadFieldName) {        String result = null;        try {            URL url = new URL(RequestURL);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setReadTimeout(TIME_OUT);            conn.setConnectTimeout(TIME_OUT);            conn.setDoInput(true);            conn.setDoOutput(true);            conn.setUseCaches(false);            conn.setRequestMethod("POST");            conn.setRequestProperty("Charset", CHARSET);            conn.setRequestProperty("connection", "keep-alive");            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());            StringBuffer sb = new StringBuffer();            sb.append(getRequestData(params));            if (file != null) {                sb.append(PREFIX);                sb.append(BOUNDARY);                sb.append(LINE_END);                sb.append("Content-Disposition: form-data; name=\"" + uploadFieldName + "\"; filename=\""+"xx"+"\"" + LINE_END);                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);                sb.append(LINE_END);            }            dos.write(sb.toString().getBytes());            if (file != null) {                InputStream is = new FileInputStream(file);                byte[] bytes = new byte[1024];                int len = 0;                while ((len = is.read(bytes)) != -1) {                    dos.write(bytes, 0, len);                }                is.close();                dos.write(LINE_END.getBytes());                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();                dos.write(end_data);            }            dos.flush();            int res = conn.getResponseCode();            Log.e(TAG, "response code:" + res);            if (res == 200) {                Log.e(TAG, "request success");                InputStream input = conn.getInputStream();                StringBuffer sb1 = new StringBuffer();                int ss;                while ((ss = input.read()) != -1) {                    sb1.append((char) ss);                }                result = sb1.toString();                Log.i(TAG, "result : " + result);            } else {                Log.e(TAG, "request error");            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }    /**     * 对post参数进行编码处理 * @param params post参数 * @return     */    private static StringBuffer getRequestData(Map<String, String> params) {        StringBuffer stringBuffer = new StringBuffer();        try {            for (Map.Entry<String, String> entry : params.entrySet()) {                stringBuffer.append(PREFIX);                stringBuffer.append(BOUNDARY);                stringBuffer.append(LINE_END);                stringBuffer.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);                stringBuffer.append(LINE_END);                stringBuffer.append(URLEncoder.encode(entry.getValue(), CHARSET));                stringBuffer.append(LINE_END);            }        } catch (Exception e) {            e.printStackTrace();        }        return stringBuffer;    }}
原创粉丝点击