Android10 Retrofit图片上传

Android10文件存储机制修改成了沙盒模式,应用不能直接访问除了沙盒文件和公共文件以外的文件,直接使用图片绝对地址上传图片会出错,可以通过图片的Uri来上传图片

    private fun copyFromUri(uri:Uri,fileName:String,subscribe:Observer<String>){
        var cacheFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath+File.separator+"cache")
        if(!cacheFile.exists())
            cacheFile.exists()
        cacheFile = File(cacheFile.absolutePath + File.separator + fileName)

        Observable.create<String>{
            val inStream:InputStream = contentResolver.openInputStream(uri)!!
            val outStream:OutputStream = FileOutputStream(cacheFile)
            val bytes = ByteArray(1024)
            var len = -1
            try {
                while ({len = inStream.read(bytes);len}()!=-1)
                    outStream.write(bytes,0,len)
            } catch (e: Exception) {
                it.onError(e)
            } finally {
                inStream.close()
                outStream.close()
            }
            it.onNext(cacheFile.path)
            it.onComplete()
        }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(subscribe)
    }

上传图片

    private fun onUpload(path: String){
        if ( "" != path.trim() ){
            val file = File(path)
            val body = file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
            val progressBody = ProgressRequestBody(body){
                progress.progress = it.toInt()
            }
            val part = MultipartBody.Part.createFormData("file",file.name,progressBody)
            getRetrofit().create(Api::class.java).onUpload(part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<ResponseBody> {
                    override fun onSubscribe(d: Disposable) {

                    }

                    override fun onNext(t: ResponseBody) {
                        Toast.makeText(this@MainActivity,"Success",Toast.LENGTH_SHORT).show()
                    }

                    override fun onError(e: Throwable) {
                        Toast.makeText(this@MainActivity,"Error!"+e.message,Toast.LENGTH_SHORT).show()
                    }

                    override fun onComplete() {
                        if(file.exists())
                            file.delete()
                    }
                })
        }
    }

网络接口定义

@Multipart
    @POST("downloadApp/upload")
    fun onUpload(@Part part:MultipartBody.Part):Observable<ResponseBody>

实现进度更新

class ProgressRequestBody(private val requestBody: RequestBody,private val listener:((Long)->Unit) ):RequestBody() {

    private var byteBufferSink:BufferedSink ?= null

    override fun contentType(): MediaType? {
        return requestBody.contentType()
    }

    override fun contentLength(): Long {
        return requestBody.contentLength()
    }

    override fun writeTo(sink: BufferedSink) {
        if (byteBufferSink == null)
            byteBufferSink = sink(sink).buffer()
        requestBody.writeTo(byteBufferSink!!)
        byteBufferSink?.flush()
    }

    private fun sink(sink:Sink) = object : ForwardingSink(sink) {

        private var count = 0L
        private var total = -1L

        @SuppressLint("CheckResult")
        override fun write(source: Buffer, byteCount: Long) {
            if (total ==-1L) total = contentLength()
            super.write(source, byteCount)
            count += byteCount
            val progress = count/total.toDouble() * 100
            Observable.just(count).observeOn(AndroidSchedulers.mainThread()).subscribe {
                listener.invoke(progress.toLong())
            }
        }
    }
}

web端的图片上传代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        String realPath = userPath + "/upload/test";
        String cachePath = userPath + "/upload/cache";

        File realFile = new File(realPath);
        File cacheFile = new File(cachePath);

        System.out.println("上传路径是:"+realPath);
        if (!realFile.exists())
            realFile.mkdirs();
        if (!cacheFile.exists())
            cacheFile.mkdirs();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(cacheFile);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        if (!ServletFileUpload.isMultipartContent(request))
            return;

        InputStream in = null;
        OutputStream out = null;
        List<String> files = new ArrayList<>();
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item:items){
                if (item.isFormField()){
                    System.out.println(item.getFieldName()+": "+item.getString("UTF-8"));
                }else {
                    String fileName = item.getName();
                    if (fileName.isEmpty()||"".equals(fileName.trim()))
                        continue;
                    fileName = fileName.substring(fileName.lastIndexOf("/")+1);
                    String downloadPath = realPath+"/"+fileName;
                    files.add(fileName);

                    in = item.getInputStream();
                    out = new FileOutputStream(downloadPath);

                    byte bt[] = new byte[1024];

                    int len = -1;

                    while ((len = in.read(bt))!=-1)
                        out.write(bt,0,len);
                }
                item.delete();
            }
        } catch (FileUploadException | IOException e) {
            System.out.println(e.getMessage());
            response.getWriter().write("ERROR");
        } finally {
            if (in!=null)
                in.close();
            if (out!=null)
                out.close();
        }
        response.getWriter().write("SUCCESS");
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,105评论 1 32
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,432评论 0 17
  • 7.1 压缩图片 一、基础知识 1、图片的格式 jpg:最常见的图片格式。色彩还原度比较好,可以支持适当压缩后保持...
    AndroidMaster阅读 2,519评论 0 13
  • 这节课是 Android 开发(入门)课程 的第四部分《数据与数据库》的第三节课,导师依然是 Jessica Li...
    HsuJin阅读 1,333评论 0 2
  • “轰”随着一声巨响,那本伫立在地面山峰瞬间土崩瓦解,那如烟雾般的尘土顷刻间便将天际覆盖。 在那漫天遍野的土黄色...
    星颜月貌阅读 207评论 0 2