There are pitfalls when downloading Alibaba Cloud OSS files to the specified local file

OSS download file code:

public void ossDownloadFile(String path){
    
    
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        File file = new File(path);

        if (!file.getParentFile().exists()){
    
    
            file.getParentFile().mkdirs();
        }
        if("/".equals(path.substring(0,1))){
    
    
            path = path.substring(1);
        }
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, path), file);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
ossClient.getObject(new GetObjectRequest(bucketName, path), file);

In the above sentence, it seems that the last parameter file should be able to specify a local file, but it seems to be limited to the local address consistent with the path, and an error will be reported after changing to another specified address:

com.eaglesoft.cfxt.common.exception.UIASException: Cannot read the content input stream.
[ErrorCode]: Unknown
[RequestId]: Unknown

Track the source code to the bottom layer, PS: This debugging is more painful, because the local cannot be debugged, and it can only be run after release to see the log records. So it's not debug, and I don't know if I'm tracking it right.
insert image description here
As can be seen from the above figure, there is no requirement for the path, and the output is directly output to the specified file. I don't know where the pit is.

Alternative solution:
The file stream can be downloaded in the OSS document, first obtain the file stream according to the key, and then use io to download to the local:

public boolean ossDownloadFileToLocal(String path,String localPath){
    
    
        File file = new File(localPath);
        if (!file.getParentFile().exists()){
    
    
            file.getParentFile().mkdirs();
        }

        log.info("localPath : " + localPath);

        if("/".equals(path.substring(0,1))){
    
    
            path = path.substring(1);
        }
        try (FileOutputStream fos = new FileOutputStream(file)){
    
    
            // 下载OSS文件流
            OSSObject object = ossClient.getObject(bucketName, path);

            InputStream is = object.getObjectContent();
            byte[] b = new byte[1024];
            int length;
            while((length= is.read(b)) != -1){
    
    
                fos.write(b,0,length);
            }

            is.close();

            // 关闭OSSClient。
            ossClient.shutdown();
        }catch (IOException e){
    
    
            throw new UIASException(e.getMessage());
        }

        return true;
    }

Guess you like

Origin blog.csdn.net/qq_16253859/article/details/106375794