上传图片到阿里云服务器

1.引入两个jar包


     com.aliyun.oss
     aliyun-sdk-oss
     2.8.0


    net.coobird
    thumbnailator
0.4.8

2.htmly页面

        


               

       

3.Controller

@RequestMapping(value = "/toUpload")
public String toUpload(HttpServletRequest request,MultipartFile file) {

    String fileName=file.getOriginalFilename();
    String imgName = createFileName(FileUtils.getFileFexName(fileName));
    try {
         InputStream inputStream = file.getInputStream();
         String savePath = FileUtils.saveAndUploadImage(inputStream, OSSClient, imgName);
        String imgUrl = ossConfig.getDownloadEndpoint() + "/" + savePath;
        return imgUrl;
    } catch (IOException e) {
   // TODO Auto-generated catch block
       e.printStackTrace();
    }

   return null;

}

 

/**
* 生产文件名 时间+8位的随机串

* @param suffix
*            后缀名
* @return
*/
public String createFileName(String suffix) {
      StringBuilder fileName = new StringBuilder();
      fileName.append(System.currentTimeMillis());
      fileName.append(MsgUtils.generateNoncestr(8));
      fileName.append(ImgTypeEnums.DEFAULT.getCode());
      fileName.append(".").append(suffix);
      return fileName.toString();
}

 

3.

public static String saveAndUploadImage(InputStream inputStream, OSSClientUtils OSSClient,
String imgName) throws IOException {
     try {
          //拼接oss服务路径hr_image/banner/
         String aliPath = BANNER_PATH_PREFIX;

          //将输入流转换图片字符流
        BufferedImage oldImage = ImageIO.read(inputStream);
        int width = oldImage.getWidth();//图片宽
       int height = oldImage.getHeight();//图片高

       //创建文件/tmp/house_image/
       File fullImg = FileUtils.createFile(new File(SAVE_PATH + imgName));


      //图片存储本地
     Thumbnails.of(oldImage).size(width, height).toFile(fullImg);
    try {
            //上传阿里oss
           OSSClient.upload(fullImg, aliPath + imgName);
          //删除本地图片
          fullImg.delete();
    } catch (Exception e) {
   logger.error("保存图片出错");
}

return aliPath + imgName;
} catch (IOException e) {
logger.error("保存图片出错");
throw e;
}


}

你可能感兴趣的:(前端)