图片上传阿里云(对象存储OSS)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片上传阿里云(对象存储OSS)相关的知识,希望对你有一定的参考价值。

 

一、资源

详细功能及使用方法,请参看“SDK手册 > Java-SDK”,
链接地址是:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/preface.html?spm=5176.docoss/sdk/java-sdk/

调用OSS Java SDK的方法时,
当错误发生时,OSS Java SDK的方法会抛出异常,异常中包括错误码、错误信息,详细请参看“SDK手册 > Java-SDK > 异常处理”,
链接地址是:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/exception.html?spm=5176.docoss/api-reference/error-response

OSS控制台可以直观的看到您调用OSS Java SDK的结果,OSS控制台地址是:https://oss.console.aliyun.com/index#/
OSS控制台使用方法请参看文档中心的“控制台用户指南”指南的链接地址是:

https://help.aliyun.com/document_detail/oss/getting-started/get-started.html?spm=5176.docoss/user_guide
 
OSS的文档中心地址:https://help.aliyun.com/document_detail/oss/user_guide/overview.html


OSS Java SDK的文档地址:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/install.html?spm=5176.docoss/sdk/java-sdk


OSS开发过程中常见问题链接地址:https://help.aliyun.com/document_detail/32024.html?spm=5176.product31815.6.665.JuvIOS

OSS Java SDK依赖下列包:

  • aliyun-sdk-oss-2.2.1.jar
  • hamcrest-core-1.1.jar
  • jdom-1.1.jar
  • commons-codec-1.9.jar
  • httpclient-4.4.1.jar(重点--版本一致)
  • commons-logging-1.2.jar
  • httpcore-4.4.1.jar(重点--版本一致)
  • log4j-1.2.15.jar(是可选的,需要日志功能的时加入该包)

若果是maven工程。则直接添加依赖即可如:

    <!-- 注意版本很重要 -->

<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.2.3</version>
        </dependency>

 

二、上代码

//oss上传图片
    public void attrcompress() throws IOException {
            
            String str=attachmentService.Upload(request, null, false);//false用来判断是否需要上传高清图片
            
            response.getWriter().write(str);//返回图片地址
            
         }
//上传的方法
  public String Upload(HttpServletRequest request, String path, Boolean is_compress) {
            List<FileItem> files = ossService.analysis(request);//从页面拿到文件list集合

            ObjectNode resultMessage = JsonUtils.createObjectNode();//声明最后返回结果的josn字符串.
            /**
             * 开始遍历request中的文件
             */
            for (FileItem file : files) {//遍历文件集合
                if (file.getName() == null) {
                    InputStream iss = null;
                    continue;
                }
                String gid = DataUtils.getUUID();
                if (is_compress) {//压缩上传保存
                    Attachment attachment_compress = this.Img_compress(file, path, gid);
                    if (attachment_compress == null) {

                        return "操作失败1";
                    } else {
                        resultMessage.set("compressAttr", JsonUtils.beanToJsonObject(attachment_compress));
                        return resultMessage.toString();
                    }
                } else if (is_compress == false) {//原图上传保存
                    Attachment attachment_source = this.Img_source(file, path, gid);
                    if (attachment_source == null) {
                        return "操作失败2";
                    } else {
                        resultMessage.set("sourceAttr", JsonUtils.beanToJsonObject(attachment_source));
                    }
                } else {//原图和压缩全部上传保存
                    Attachment attachment_compress = this.Img_compress(file, path, gid);
                    Attachment attachment_source = this.Img_source(file, path, gid);
                    if (attachment_compress == null && attachment_source == null) {
                        return "操作失败3";
                    } else {
                        resultMessage.set("sourceAttr", JsonUtils.beanToJsonObject(attachment_source));
                        resultMessage.set("compressAttr", JsonUtils.
                                          beanToJsonObject(attachment_compress));
                        return resultMessage.toString();
                    }
                }
            }
            if (resultMessage.isNull()) {
                return "操作失败4";
            } else {
                return resultMessage.toString();
            }

        }
        
           //获取请求参数
        public List<FileItem> analysis(HttpServletRequest request) {
            List<FileItem> list = new ArrayList<FileItem>();
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<?> uploadFiles;
                //uploadFiles获取请求参数为空,缘为springMvc已配读取,此处为二次读取,所以为空
                uploadFiles = upload.parseRequest(request);
                Iterator<?> iterator = uploadFiles.iterator();
                while (iterator.hasNext()) {
                    Object object = iterator.next();
                    if (object instanceof FileItem) {
                        list.add((FileItem) object);
                    }
                }
            } catch (FileUploadException fue) {
//                log.error("文件上传请求数据解析失败", fue);
                 fue.printStackTrace();
            }
            return list;
        }
//处理文件流
     private Attachment Img_compress(FileItem file, String path, String gid) {
            String id = DataUtils.getUUID();
            if (path == null) {
                path = "/temp/" + id;
            }
            /**
             * 获取到图片格式
             */
            String attrName = file.getName();    // 附件的名称
            String attType = attrName.substring(attrName.lastIndexOf(".") + 1);
            /**
             * 获取到图片模块
             */
            String moudelName = file.getFieldName(); // 获得附件的模块名称
            /**
             * 定义压缩图的名称
             */
            String compressAttName = moudelName + "_compress" + "." + attType;//定义缩略图的名称

            /**
             * 开始压缩
             */
            int width = 500;
            int heigth = 500;
            ByteArrayInputStream in = null;

            try (ByteArrayOutputStream out = new ByteArrayOutputStream(file.get().length)) {
                Image img = ImageIO.read(file.getInputStream());
                if (img.getWidth(null) == -1) {
                    return null;
                } else {
                    int newWidth;
                    int newHeight;
                    double rate1 = ((double) img.getWidth(null)) / (double) width
                                           + 0.1;
                    double rate2 = ((double) img.getHeight(null)) / (double) heigth
                                           + 0.1;
                    // 根据缩放比率大的进行缩放控制   
                    double rate = rate1 > rate2 ? rate1 : rate2;
                    newWidth = (int) (((double) img.getWidth(null)) / rate);  //将大于规定尺寸的图片缩小,将小于规定尺寸的图片放大
                    newHeight = (int) (((double) img.getHeight(null)) / rate);
                    BufferedImage tag = new BufferedImage(newWidth, newHeight,
                                                          BufferedImage.TYPE_INT_RGB);
                    img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
                    tag.getGraphics().drawImage(img.getScaledInstance(newWidth,
                                                                      newHeight,
                                                                      Image.SCALE_SMOOTH),
                                                0,
                                                0, null);
                    ImageWriter imgWrier;  //创建压缩的图片,用来编码和写入图像的抽象超类。此类必须由在 Java Image I/O 框架的上下文中写出图像的类为其创建子类。 
                    ImageWriteParam imgWriteParams;
                    imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
                    imgWriteParams
                            = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
                                    null);
                    imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    imgWriteParams.setCompressionQuality(0.3f);
                    imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
                    ColorModel colorModel = ColorModel.getRGBdefault();
                    imgWriteParams.setDestinationType(
                            new javax.imageio.ImageTypeSpecifier(
                                    colorModel, colorModel.
                                            createCompatibleSampleModel(100, 100)));
                    imgWrier.reset();
                    imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                    imgWrier.write(null, new IIOImage(tag, null, null),
                                   imgWriteParams);
                    out.flush();
                    in = new ByteArrayInputStream(out.toByteArray());
                    //        out.close();  
                }
            } catch (IOException e) {
                e.printStackTrace();
//                log.warn("图片压缩出现问题", e);
            }
            //上传保存压缩图片

            String url = ossService.uploadFile(path, in, compressAttName);//将附件保存到oss服务器(Url/文件/文件名)
            Attachment attr = new Attachment();
            attr.setId(id);
            attr.setAtt_name(compressAttName);
            attr.setAtt_path(url);
            attr.setMoudel_name(moudelName);
            attr.setAtt_type(attType);
            attr.setUpload_time(DateUtils.getSystemDate());
            attr.setDownload_count(0);
            attr.setGid(gid);
            attr.setIs_compress(1);
//            this.saveAttachmentDao(attr);
//            Boolean flag = this.contains(attr);
            if (attr!=null) {
                return attr;
            }else{
                 return null;
            } 
          
        }

           //上传文件
        public String uploadFile(String uploadPath, InputStream input, String fileName) {
            String uploadPathName = processingPath(uploadPath) + DataUtils.getUUID();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentDisposition("attachment;filename=" + fileName);
            getOssClient().putObject(bucketName, uploadPathName, input, metadata);
            return getHttpURLByFileKey(uploadPathName);
        }

        //实例化服务端对象(oss)
          public OSSClient getOssClient() {
            if (client == null) {
                ClientConfiguration conf = new ClientConfiguration();
                conf.setConnectionTimeout(timeout);
                conf.setMaxErrorRetry(3);
                client = new OSSClient(endpoint, accessKeyId, accessKeySecret);//oss应用所需参数
            }
            return client;
        }

 

以上是关于图片上传阿里云(对象存储OSS)的主要内容,如果未能解决你的问题,请参考以下文章

上传图片到阿里云oss

阿里OSS对象---头像上传

阿里OSS对象---头像上传

阿里OSS对象---头像上传

使用axios上传文件到阿里云对象文件存储服务器oss

阿里云对象存储 OSS-base64 上传