标签:标记 content load try 服务器 ble public encrypt lock
对阿里云OSS上传小文件时的进度,想过两个方法:一是。通过多线程监測Inputstream剩余的字节数来计算,可是由于Inputstream在两个线程中共用,假设上传线程将Inputstream关闭,在监測线程就会报“句柄无效”的错误,甚至会导致上传失败;第二个方法是通过线程不断监測OSS上已经上传文件的大小,可是在文件全然上传前是不能获得文件大小的。
最后突然灵感来了,把两个方法同一时候使用就行监測文件上传的进度。看代码:
// 上传小文件 private static void uploadSmallFile(final OSSClient client, final String bucketName, final String key, final File uploadFile) throws OSSException, ClientException, FileNotFoundException { ObjectMetadata objectMeta = new ObjectMetadata(); objectMeta.setContentLength(uploadFile.length()); // 可以在metadata中标记文件类型 objectMeta.setContentType("application/pdf"); //对object进行服务器端加密。眼下服务器端仅仅支持x-oss-server-side-encryption加密 objectMeta.setHeader("x-oss-server-side-encryption", "AES256"); final InputStream input = new FileInputStream(uploadFile); Thread t = new Thread(new Runnable() { @Override public void run() { InputStream tmpInput = null; while(true){ //将input缓存在tmpInput中,防止在调用available()方法是异常导致上传失败 tmpInput = input; try { Thread.sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if(input!=null){ System.out.println(uploadFile.getName()+"的上传进度为"+(float)(uploadFile.length()-tmpInput.available())/uploadFile.length()); if(tmpInput.available() == 0){ break; } }else{ break; } } catch (IOException e) { break; } } //通过获取oss上文件的大小来推断是否上传成功,假设不能从oss获得文件的大小说明上传失败 try{ ObjectMetadata tmpObjectMeta = client.getObjectMetadata(bucketName, key); System.out.println(uploadFile.getName()+"的上传进度为:"+tmpObjectMeta.getContentLength()/uploadFile.length()); }catch(Exception e){ e.printStackTrace(); System.out.println(uploadFile.getName()+"上传失败"); } } }); t.start(); PutObjectResult result =client.putObject(bucketName, key, input, objectMeta); String md5 = null; try { md5 = DigestUtils.md5Hex(new FileInputStream(uploadFile)); System.out.println("MD5:"+ md5); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("上传的object返回的E_tag:"+result.getETag()); System.out.println("上传是否成功:"+ md5.equalsIgnoreCase(result.getETag())); }
标签:标记 content load try 服务器 ble public encrypt lock
原文地址:http://www.cnblogs.com/claireyuancy/p/7136965.html