【java】上传数据到阿里云的OSS

需要上传的文件分为两种:

  1. 本地文件上传:只需要按照OSS中上传数据的文档直接编写即可
  2. 网上数据上传:如果上传的数据来自网络则需要将其下载到本地,
    public String Upload(String word,String path) throws FileNotFoundException {
        // 判断是否有文件
        File file=new File(path);
        if (word.isEmpty()) {
            return null;
        }
        // 图片的新名字
        String fileName=word+IdWorker.getIdStr()+ file.toString().substring(file.toString().lastIndexOf('.'));
        // 服务器保存位置
        File newFile=file;
        if(FILE_FORMAT.contains(path.substring(path.lastIndexOf('.') + 1).toUpperCase())) {
            try {
                // 判断上传地址是否为网络
                if (!file.exists()) {
                    newFile = new File("E:\\" + fileName);
                    URL url = new URL(path);
                    DataInputStream dis = new DataInputStream(url.openStream());
                    OutputStream os = new FileOutputStream(newFile);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dis.read(buffer)) > 0) {
                        os.write(buffer, 0, length);
                    }
                    os.close();
                    dis.close();
                }
                // 判断上传图片是否大于1MB
                if (file.length() > 1024 * 1024) {
                    // 读取文件
                    BufferedImage bufImage = ImageIO.read(newFile);
                    //获取缩放比例
                    int wr = (int) (bufImage.getWidth() * 1024 * 1024 / file.length());
                    int hr = (int) (bufImage.getHeight() * 1024 * 1024 / file.length());
                    bufImage.getScaledInstance(wr, hr, Image.SCALE_AREA_AVERAGING);
                    // 把修改过的 bufImage 保存到本地
                    ImageIO.write(bufImage, "JPG", newFile);

                }
            } catch (Exception e) {
                System.out.println("异常");
            }
        }
        // 将图片保存到OSS
        ObjectMetadata objectMetadata = new ObjectMetadata();

        // 生成路径
        String name=words+word+"/"+fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        InputStream inputStream = new FileInputStream(newFile);
        ossClient.putObject(bucketname, app+name, inputStream, objectMetadata);

        // 关闭OSSClient。
        ossClient.shutdown();
        return name;
    }

PS:其中word是一个标志,可有可无,如果删除需要将代码中相应的word全部删除,path是需要上传文件的路径。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章