美文网首页
文件上传

文件上传

作者: HOLLE_karry | 来源:发表于2020-05-13 20:53 被阅读0次

1.导依赖

 //okhttp
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    //butterknife
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    //glide
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    //gson
implementation 'com.google.code.gson:gson:2.2.4'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0' // 必要依赖,解析json字符所用
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' // 必要依赖,和Rxjava结合必须用到,下面会提到
implementation "io.reactivex.rxjava2:rxjava:2.1.3" // 必要rxjava2依赖
implementation "io.reactivex.rxjava2:rxandroid:2.0.1" // 必要rxandrroid依赖,切线程时需要用到

2.OK上传

private void okHttpUpload() {
        //上传一个sd卡图片,处理权限
        //注意文件位置
        File file = new File("/storage/emulated/legacy/Pictures/g.png");
        //ok 网络请求, okhttpclinet.newCall().enqueue()
        //提交文件的请求,里面含文件
        MediaType parse = MediaType.parse("application/octet-stream");
        RequestBody fileBody = RequestBody.create(parse, file);
        //分块请求的请求体
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("key", "857")//指定服务器保存图片的文件夹
                .addFormDataPart("file", file.getName(), fileBody)//上传的文件
                .build();

        Request request = new Request.Builder()
                .url(mUrl)
                .post(body)
                .build();

        mOkHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "onFailure: " + e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "onResponse: " + response.body().string());
                    }
                });
    }

3.Retrofit上传

//底层是ok
    private void retrofitUpload() {
        File file = new File("/storage/emulated/legacy/Pictures/o.jpg");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MediaType parse = MediaType.parse("application/octet-stream");
        RequestBody requestBody = MultipartBody.create(parse, file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        new Retrofit.Builder()
                .baseUrl(ApiService.url_up)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(ApiService.class)
                .getUp(part)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String string = response.body().string();
                            Log.e(TAG, "onResponse: " + string);
                            String[] split = string.split("<br />");
                            String s = split[split.length - 1];
                            UpBean upBean = new Gson().fromJson(s, UpBean.class);
                            Glide.with(LoadActivity.this).load(upBean.getData().getUrl()).into(iv);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
    }

4.HttpUrlCollection上传

HashMap<String, String> map = new HashMap<>();
                map.put("key", "666");
                File file = new File("/storage/emulated/legacy/Pictures/g.png");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        uploadForm(null, "file", file, "xxx.jpg", mUrl);
                    }
                }).start();

public void uploadForm(Map<String, String> params, String fileFormName, File uploadFile, String newFileName, String urlStr) {
        if (newFileName == null || newFileName.trim().equals("")) {
            newFileName = uploadFile.getName();
        }
        StringBuilder sb = new StringBuilder();
        /**
         * 普通的表单数据
         */
        if (params != null) {
            for (String key : params.keySet()) {
                sb.append("--" + BOUNDARY + "\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n");
                sb.append("\r\n");
                sb.append(params.get(key) + "\r\n");
            }
        }

        try {
            /**
             * 上传文件的头
             */
            sb.append("--" + BOUNDARY + "\r\n");
            sb.append("Content-Disposition: form-data; name=\"" + fileFormName + "\"; filename=\"" + newFileName + "\""+ "\r\n");
            sb.append("Content-Type: application/octet-stream" + "\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentType
            sb.append("\r\n");
            byte[] headerInfo = sb.toString().getBytes("UTF-8");
            byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
            URL url = null;
            url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            // 设置传输内容的格式,以及长度
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("Content-Length",String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            InputStream in = new FileInputStream(uploadFile);
            //写入的文件长度
            int count = 0;
            //文件的总长度
            int available = in.available();
            // 写入头部 (包含了普通的参数,以及文件的标示等)
            out.write(headerInfo);
            // 写入文件
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                count += len;
                int progress = count * 100 / available;
                Log.d(TAG, "上传进度: " + progress + " %");
            }
            // 写入尾部
            out.write(endInfo);
            in.close();
            out.close();
            if (conn.getResponseCode() == 200) {
                System.out.println("文件上传成功");
                String s = stream2String(conn.getInputStream());
                Log.d(TAG, "uploadForm: " + s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

5.拍照上传

//拍照上传,注意危险权限处理
    private void takePhoto() {
        if (PackageManager.PERMISSION_GRANTED ==
                ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
            //有权限
            openCamera();
        } else {
            //没有权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, 200);
        }
    }
//开启相机
    private void openCamera() {
        //系统所有的界面都是activity,启动activity方式几种?
        //显示启动:指名道姓的启动
        //new Intent(this,MainActivity.class)
        //隐式启动:不指名道姓,匹配的方式,data,category,action,系统的界面一般都是隐式启动
        //创建文件用于保存图片
        mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
        if (!mFile.exists()) {
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //适配7.0以上
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mImageUri = Uri.fromFile(mFile);
        } else {
            //第二个参数要和清单文件中的配置保持一致
            //私有目录访问受限,需要清单文件配置ContentProvider
            //如果不配置,会报FileUriExposedException: file:///storage/emulated/0/Android/data/com.xts.upload/cache/1589178590497.jpg
            mImageUri = FileProvider.getUriForFile(this, "com.example.upload", mFile);
        }

        //启动相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将拍照图片存入mImageUri
        startActivityForResult(intent, CAMERA_CODE);
    }

6.相册上传

//开启相册选取图片上传
    private void album() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, ALBUM_CODE);
    }

相关文章

网友评论

      本文标题:文件上传

      本文链接:https://www.haomeiwen.com/subject/stponhtx.html