多文件的上传 Android客户端与java服务端

客户端

ProgressListener

public interface ProgressListener {
    void onProgress(long hasWrittenLen, long totalLen, boolean hasFinish) throws InterruptedException;
}

DefaultProgressListener

public class DefaultProgressListener implements ProgressListener {

    private Handler mHandler;

    //多文件上传时,index作为上传的位置的标志
    private int mIndex;

    public DefaultProgressListener(Handler mHandler, int mIndex) {
        this.mHandler = mHandler;
        this.mIndex = mIndex;
    }

    @Override
    public void onProgress(long hasWrittenLen, long totalLen, boolean hasFinish) throws InterruptedException {
        System.out.println("----the current " + hasWrittenLen + "----" + totalLen + "-----" + (hasWrittenLen * 100 / totalLen));



        int percent = (int) (hasWrittenLen * 100 / totalLen);
        //int percent = (int) (ConStant.LASTSIZE * 100 / ConStant.LOADSIZE);
        if (percent > 100) percent = 100;
        if (percent < 0) percent = 0;

        ConStant.UPDATERATE=hasWrittenLen-ConStant.UPSIZE;
        ConStant.LASTSIZE=ConStant.LASTSIZE+ConStant.UPDATERATE;
        if(hasWrittenLen == totalLen) {
            ConStant.UPSIZE = 0;
        }
        else
        {
            ConStant.UPSIZE = hasWrittenLen;
        }

        Message msg = Message.obtain();
        msg.what = (int) (ConStant.LASTSIZE * 100 / ConStant.LOADSIZE);
        msg.arg1 = mIndex;
        mHandler.sendMessage(msg);
        //Thread.sleep(1000);
    }

}

UploadFileRequestBody

public class UploadFileRequestBody extends RequestBody {

    private RequestBody mRequestBody;
    private ProgressListener mProgressListener;

    private BufferedSink bufferedSink;


    public UploadFileRequestBody(File file , ProgressListener progressListener) {
        this.mRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file) ;
        this.mProgressListener = progressListener ;
    }

    public UploadFileRequestBody(RequestBody requestBody, ProgressListener progressListener) {
        this.mRequestBody = requestBody;
        this.mProgressListener = progressListener;
    }

    //返回了requestBody的类型,想什么form-data/MP3/MP4/png等等等格式
    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    //返回了本RequestBody的长度,也就是上传的totalLength
    @Override
    public long contentLength() throws IOException {
        return mRequestBody.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            //包装
            bufferedSink = Okio.buffer(sink(sink));
        }
        //写入
        mRequestBody.writeTo(bufferedSink);
        //必须调用flush,否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //当前写入字节数
            long bytesWritten = 0L;
            //总字节长度,避免多次调用contentLength()方法
            long contentLength = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0) {
                    //获得contentLength的值,后续不再调用
                    contentLength = contentLength();
                }
                //增加当前写入的字节数
                bytesWritten += byteCount;
                //回调上传接口
                try {
                    mProgressListener.onProgress(bytesWritten, contentLength, bytesWritten == contentLength);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}

UpdateFile读取文件

public class UpdateFile {

    public static List<File> getFile(File file) {
        File[] fileArray = file.listFiles();
        List<File> mFileList = new ArrayList<File>();
        for (File f : fileArray) {
            if (f.isFile()) {
                ConStant.LOADSIZE=ConStant.LOADSIZE+f.length();
                mFileList.add(f);
            } else {
                getFile(f);
            }
        }
        return mFileList;
    }

    public static List<MultipartBody.Part> filesToMultipartBodyParts(String url,String datas) {

        File f = new File(url);
        List<File> fileList = getFile(f);
        List<MultipartBody.Part> parts = new ArrayList<>(fileList.size());
        for (File file : fileList) {
            UploadFileRequestBody requestBody = new UploadFileRequestBody(file, new DefaultProgressListener(mHandler,1));
            //RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData(file.getName(), file.getName(), requestBody);
            parts.add(part);
        }

        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),datas);
        UploadFileRequestBody requestBody = new UploadFileRequestBody(body, new DefaultProgressListener(mHandler,1));
        MultipartBody.Part part = MultipartBody.Part.createFormData("datas", "datas", requestBody);
        parts.add(part);

        return parts;
    }



}

监听读取(滚动条)

public static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bl = msg.getData();
            switch (msg.arg1) {
                case 1:
                    if (msg.what > 0) {
                        pb.setProgress(msg.what);
                        tx_rate.setText(msg.what+"%");
                    }
                    break;
            }
        }
    };

rxjava与Retrofit

Subscription rxSubscription =mRetrofitHelper.saveAllData(filesToMultipartBodyParts(FileUtil.photoPath,datas)).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new CommonSubscriber<ResponseBody>(mView) {
                    @Override
                    public void onCompleted() {}

                    @Override
                    public void onError(Throwable e) {
                        System.out.println("---the error is ---" + e);
                    }

                    @Override
                    public void onNext(ResponseBody s) {
                        //try {
                            mView.showToast("数据上传成功");
                        /*} catch (IOException e) {
                            e.printStackTrace();
                        }*/
                    }
                });
        saveSubscription("sendFile", rxSubscription);


public Observable<ResponseBody> saveAllData(List<MultipartBody.Part> body) {
        return mMapSayApiService.saveAllData(body);
    }


 @Multipart
    @POST("cjData/saveAllData")
    Observable<ResponseBody> saveAllData(@Part() List<MultipartBody.Part> parts);

服务端


@RequestMapping(value = "saveAllCjData")
    public @ResponseBody Object saveAllCjData(MultipartHttpServletRequest request, HttpServletResponse response,Model model)throws IOException, ParseException, FileUploadException {
        request.setCharacterEncoding("UTF-8");              

        Iterator<String> iter = request.getFileNames(); 
        while(iter.hasNext()){  
            MultipartFile file = request.getFile(iter.next());
            if(file != null){  
                //取得当前上传文件的文件名称  
                String myFileName = file.getOriginalFilename();
                if(myFileName.equals("datas"))//获取遍历json
                {
                    String jsonData = getData(file);                                                                            
                    JSONObject obj = new JSONObject (jsonData);
                    Iterator it = obj.keys();  
                    while (it.hasNext()) {
                        String key = (String) it.next(); 
                        //String value = obj.getString(key);  
                        JSONArray array = obj.getJSONArray(key);  
                        switch (key){

                        }
                    }
                }
                else
                {                   
                    // 输入流  
                    InputStream is = file.getInputStream();  

                    // 1K的数据缓冲  
                    byte[] bs = new byte[1024];  
                    // 读取到的数据长度  
                    int len;  
                    // 输出的文件流  
                   File sf=new File(request.getSession().getServletContext().getRealPath("/userfiles")+"\\sendFiles");  
                   if(!sf.exists()){  
                       sf.mkdirs();  
                   }  
                   OutputStream os = new FileOutputStream(sf.getPath()+"\\"+file.getOriginalFilename());  
                    // 开始读取  
                    while ((len = is.read(bs)) != -1) {  
                      os.write(bs, 0, len);  
                    }  
                    // 完毕,关闭所有链接  
                    os.close();  
                    is.close(); 
                } 
            }
        }


        Map<String,Object> json=new HashMap<String,Object>();
        json.put("code", "200");    
        return json;
    }

public String getData(MultipartFile file){
        String result = null;
        try {
            //包装request的输入流
            BufferedReader br = new BufferedReader(  
              new InputStreamReader((ByteArrayInputStream) file.getInputStream(), "utf-8"));
            //缓冲字符
            StringBuffer sb=new StringBuffer("");
            String line;
            while((line=br.readLine())!=null){
                sb.append(line);
            }
            br.close();//关闭缓冲流
            result=sb.toString();//转换成字符
            System.out.println("result = " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }   
            return result;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值