oss文件上传带进度条

参考:https://blog.csdn.net/weixin_37264997/article/details/82285124

​
public class OssUploadUtil
{
	private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "xxx";
    private static String accessKeySecret = "xxxxx";
    private static String bucketName = "xxx";
    private static String filePath = "xxx";


	public static String fileUpload(File file, String key, HttpServletRequest request)
	{
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		String filePathName  = filePath+"/"+key;
		try {
			/*
			 * Determine whether the bucket exists
			 */
			if (!ossClient.doesBucketExist(bucketName)) {
				/*
				 * Create a new OSS bucket
				 */
				System.out.println("Creating bucket " + bucketName + "\n");
				ossClient.createBucket(bucketName);
				CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
				createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
				ossClient.createBucket(createBucketRequest);
			}
			
			/*
			 * List the buckets in your account
			 */
			System.out.println("Listing buckets");
			
			ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
			listBucketsRequest.setMaxKeys(500);
			
			for (Bucket bucket : ossClient.listBuckets()) {
				System.out.println(" - " + bucket.getName());
			}
			
			/*
			 * Upload an object to your bucket
			 */
			System.out.println("Uploading a new object to OSS from a file\n");
			/*
			        这里用带进度条的OSS上传 
			        将session传入PutObjectProgressListener的构造中!官网例子是没有这个操作的
			        注意new PutObjectRequest()的第三个参数是File而不是官网介绍的FileInputStream,否则获取不到进度.
	       */
           ossClient.putObject(new PutObjectRequest(bucketName, key, file).
	                       <PutObjectRequest>withProgressListener(new PutObjectProgressListener(request.getSession())));
		} catch (OSSException oe) {
			oe.printStackTrace();
			System.out.println("Caught an OSSException, which means your request made it to OSS, "
					+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message: " + oe.getErrorCode());
			System.out.println("Error Code:       " + oe.getErrorCode());
			System.out.println("Request ID:      " + oe.getRequestId());
			System.out.println("Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			ce.printStackTrace();
			System.out.println("Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message: " + ce.getMessage());
			System.out.println(ce.getMessage());
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			ossClient.shutdown();
		}
		
		return filePathName;
	}
	
	/**
     * The uploading progress listener. Its progressChanged API is called by the SDK when there's an update.
     */
    static class PutObjectProgressListener implements ProgressListener {

    	private HttpSession session;
        private long bytesWritten = 0;
        private long totalBytes = -1;
        private boolean succeed = false;
        private int percent = 0;
        
      //构造方法中加入session
        public PutObjectProgressListener() {
        }
        public PutObjectProgressListener(HttpSession mSession) {
            this.session = mSession;
            session.setAttribute("upload_percent", percent);
        }
        
        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                System.out.println("Start to upload......");
                break;
            
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
                break;
            
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
                 	//将进度percent放入session中
                    session.setAttribute("upload_percent", percent);
                    System.out.println(bytes + " bytes have been written at this time, upload progress: " +
                            percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
                    System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown" +
                            "(" + this.bytesWritten + "/...)");
                }
                break;
                
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
                break;
                
            case TRANSFER_FAILED_EVENT:
                System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                break;
                
            default:
                break;
            }
        }

        public boolean isSucceed() {
            return succeed;
        }
    }
    

}

​

控制层:

@Controller
@RequestMapping("/file")
public class FileUploadAction extends BaseAction
{
	
	@ResponseBody
	@RequestMapping("upload")
	public Map<String,Object> upload(HttpServletRequest req,@RequestParam MultipartFile file) throws IOException {
		//上传到阿里云OSS
		File sampleFile=null;
		if(file.getSize()>10000){
			CommonsMultipartFile cf= (CommonsMultipartFile)file; 
			DiskFileItem diskFileItem = (DiskFileItem)cf.getFileItem(); 
			sampleFile = diskFileItem.getStoreLocation();
		}else{
			String path=req.getSession().getServletContext().getRealPath("/upload");
			sampleFile=new File(path+file.getOriginalFilename());
			file.transferTo(sampleFile);
		}
		String oldName=file.getOriginalFilename();
		String suffix=oldName.substring(oldName.lastIndexOf("."));
	    Map map=FileUtil.upload(sampleFile, suffix, req);		
		return map;
	}
	
	 /**
     * 获取实时长传进度
     * @param request
     * @return
     */
    @RequestMapping ("item/percent")
    @ResponseBody
    public int getUploadPercent(HttpServletRequest request){
        HttpSession session = request.getSession();
        int percent = session.getAttribute("upload_percent") == null ? 0:  (Integer)session.getAttribute("upload_percent");
        return percent;
    }

    /**
     * 重置上传进度
     * @param request
     * @return
     */
    @RequestMapping ("/percent/reset")
    public void resetPercent(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("upload_percent",0);
    }
}

js调用:

var intervalId = setInterval(function () {
	            $.get("${base}/file/item/percent", {}, function (data) {
	                console.log(data);
	                var percent = data;
	                if (percent >= 100) {
	                    clearInterval(intervalId);
	                    percent = 100;//不能大于100
	                }
	                $('#id_percent').val(percent);
	            }, "json");
            }, 100);

猜你喜欢

转载自blog.csdn.net/zhangyongbink/article/details/86236323