前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

方案

先缓存到本地,再放到服务器

package com.duodian.youhui.admin.utils;

import com.duodian.youhui.admin.Exceptions.AppException;
import com.duodian.youhui.admin.constants.SystemParams;
import com.duodian.youhui.admin.utils.qCode.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;

/**
 * 作者 :HealerJean
 * 日期 :2019/1/16  下午7:01.
 * 类描述:
 */
@Slf4j
@Service
public class ImageUploadUtils {


    /**
     * 先缓存到本地再上传到阿里云oss服务器
     * @param imgUrl
     * @return
     */
    public static String uploadUrlToAliyun(String imgUrl) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        File file = null ;
        try {

      
            URL url = new URL(StringEscapeUtils.unescapeHtml(netUrl));
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(30*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream  stream = conn.getInputStream();
            

            //上传到阿里云服务器
            String fileLink = "admin/duodianyouhui/imgurl" + StringGeneratorUtil.generate() + ".jpg" ;
            OSSUploader.upload(fileLink,stream);


            // return SystemParams.OSS_HOST+ fileLink ;
            return  fileLink ;

        } catch (FileNotFoundException e) {
            throw  new AppException("文件流出错");
        }catch (Exception e){
            ExceptionLogUtils.log(e,ImageUploadUtils.class );
            throw  new AppException(e.getMessage());
        }finally { //关闭不必要的连接

            //图片生成将服务器文件删除
            if(file.exists()){
                file.delete();
            }
            try {
                if(inputStream!=null) {
                    inputStream.close();
                }if(outputStream!=null){
                    outputStream.close();
                }
                inputStream = null ; //关闭并置空
                outputStream = null; //关闭并置空
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


ContactAuthor