美文网首页我爱编程
spring boot 集成阿里云上传图片

spring boot 集成阿里云上传图片

作者: 周六不算加班 | 来源:发表于2018-06-10 12:34 被阅读760次

    1、properties文件阿里云配置
    accesskeyid=xxxxxx
    accesskeysecret=xxxxxxx
    bucket=xxx
    endpoint=oss-cn-beijing.aliyuncs.com
    protocol=http
    domain=dysmsapi.aliyuncs.com
    product=Dysmsapi
    starpoint = xxxx

    2、pom文件加入相关的jar包
    <dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.1</version>
    </dependency>

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>   
    

    3、建立阿里云的model包,在这个包里面建两个class, 一个来接受配置文件的阿里云的配置,一个来接受返回的值。

    ALiYunOss来接受配置文件中的配置。
    @Component
    @Configuration
    public class ALiYunOss {
        @Value("${bucket}")
        private String bucket;
        @Value("${accesskeyid}")
        private String accesskeyid;
        @Value("${accesskeysecret}")
        private String accesskeysecret;
        @Value("${endpoint}")
        private String endpoint;
        @Value("${protocol}")
        private String protocol;
        @Value("${domain}")
        private String customdomain;
        @Value("${starpoint}")
        private String starpoint;
        @Value("${product}")
        private String product;
    
        public String getProduct() {
            return product;
        }
    
        public void setProduct(String product) {
            this.product = product;
        }
    
        /**
         * 协议
         * 
         * @return
         */
        
        public String getAccesskeyid() {
            return accesskeyid;
        }
    
        public void setAccesskeyid(String accesskeyid) {
            this.accesskeyid = accesskeyid;
        }
    
        public String getAccesskeysecret() {
            return accesskeysecret;
        }
    
        public void setAccesskeysecret(String accesskeysecret) {
            this.accesskeysecret = accesskeysecret;
        }
        
        public String getProtocol() {
            return protocol;
        }
    
        public String getBucket() {
            return bucket;
        }
    
        public void setBucket(String bucket) {
            this.bucket = bucket;
        }
    
    
        public String getEndpoint() {
            return endpoint;
        }
    
        public void setEndpoint(String endpoint) {
            this.endpoint = endpoint;
        }
    
        public String getStarpoint() {
            return starpoint;
        }
    
        public void setStarpoint(String starpoint) {
            this.starpoint = starpoint;
        }
    
        /**
         * 协议
         * 
         * @return
         */
        public void setProtocol(String protocol) {
            this.protocol = protocol;
        }
    
    
        /**
         * 获取域名
         * 
         * @return
         */
        public String getDomain() {
            if (StringUtils.isEmpty(customdomain))
                return getEndpoint().replace(getProtocol() + "://", getProtocol() + "://" + getBucket() + ".");
            else
                return this.customdomain;
    
        }
        
        
        public String getCustomdomain() {
            return customdomain;
        }
        
        /**
         * 自定义域名,如果存在自定义域名,则直接使用自定义域名
         * 
         * @return
         */
    
        public void setCustomdomain(String customdomain) {
            this.customdomain = customdomain;
        }
    
        /**
         * 获取图片路径
         * 
         * @return
         */
        public String getPoint(){
            return (this.protocol+"://"+this.starpoint+"."+this.endpoint+"/");
        }
        
    
    }
    
    OSS返回数据
    public class OSSResultModel {
        private String url = "";
        private String path = "";
        private String host = "";
    
        /**
         * 完整URL地址
         * 
         * @return
         */
        public String getUrl() {
            return url;
        }
    
        /**
         * 完整URL地址
         * 
         * @return
         */
        public void setUrl(String url) {
            this.url = url;
        }
    
        /**
         * 相对路径
         * 
         * @return
         */
        public String getPath() {
            return path;
        }
    
        /**
         * 相对路径
         * 
         * @return
         */
        public void setPath(String path) {
            this.path = path;
        }
    
        /**
         * 主机地址
         * 
         * @return
         */
        public String getHost() {
            return host;
        }
    
        /**
         * 主机地址
         * 
         * @return
         */
        public void setHost(String host) {
            this.host = host;
        }
    
    }
    

    4、创建文件管理接口
    @Component
    public interface FileServiceInterFace {
    /**
    * 上传数据流
    *
    * @param inputStream
    * @return
    */
    OSSResultModel saveFile(String key, InputStream inputStream);

        /**
         * 上传文件
         * 
         * @param file
         * @return
         */
        OSSResultModel saveFile(String key, File file);
    
        /**
         * 上传Byte流
         * 
         * @param byteArrayInputStream
         * @return
         */
        OSSResultModel saveFile(String key, ByteArrayInputStream byteArrayInputStream);
    
        /**
         * 上传字符串
         * 
         * @param string
         * @return
         */
        OSSResultModel saveFile(String key, String string);
    
        /**
         * 上传网络流
         * 
         * @param url
         * @return
         */
        OSSResultModel saveFile(String key, URL url);
    }
    

    5、实现阿里云服务上传图片
    @Service
    public class ALIOSSFileService implements FileServiceInterFace {

        @Autowired
        private ALiYunOss aLiYunOss;
    
        
    
        @Override
        public OSSResultModel saveFile(String key, InputStream inputStream) {
            
            OSSResultModel ossResult = new OSSResultModel();
            OSSClient ossClient = new OSSClient(aLiYunOss.getEndpoint(), aLiYunOss.getAccesskeyid(),
                    aLiYunOss.getAccesskeysecret());
            String ossKey = "f/" + key.hashCode() % 64 + "/" + key;
            ossClient.putObject(aLiYunOss.getBucket(), ossKey, inputStream);
            // 关闭client
            ossClient.shutdown();
            // http://abugong-uploadtest.oss-cn-shanghai.aliyuncs.com/a
            ossResult.setPath(ossKey);
            ossResult.setHost(aLiYunOss.getDomain());
            ossResult.setUrl(aLiYunOss.getPoint()+ ossResult.getPath());
            return ossResult;// aiYunOss.getEndpoint().replace("http://", "http://"
                                // + aiYunOss.getBucket() + ".") + "/" + ossKey;
        }
    
        @Override
        public OSSResultModel saveFile(String key, File file) {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public OSSResultModel saveFile(String key, ByteArrayInputStream byteArrayInputStream) {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public OSSResultModel saveFile(String key, String string) {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public OSSResultModel saveFile(String key, URL url) {
            // TODO Auto-generated method stub
            return null;
        }
    
    }
    

    6、实现阿里云上传图片工具类
    @Component
    public class FileUtils {

        @Autowired
        FileServiceInterFace aLIOSSFileService;
        
        /**
         * 文件copy方法
         * @param src
         * @param dest
         */
        public  void copy(InputStream src, OutputStream dest) {
            try {
                byte[] tmp = new byte[1024];
                int len = -1;
                while ((len = src.read(tmp)) != -1)
                    dest.write(tmp, 0, len);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        
        /**
         * 给文件重命名 防止覆盖
         * @param fileName
         * @return 时间戳+原始文件的后缀
         */
        public  String reName(String fileName){
            return new StringBuffer().append(new Date().getTime()).append(fileName.substring(fileName.indexOf("."))).toString();
        }
        
        /**
         * 文件保存
         * @param fileName reName之后的文件名称
         * @param content 
         * @param filePath 文件保存路径
         * @return 
         * @throws IOException
         */
        public OSSResultModel saveFile(String fileName, InputStream content) throws IOException {
            FileOutputStream fos = null;
            OSSResultModel ossResul = null;
             try {
                //上传到oss
                 ossResul = aLIOSSFileService.saveFile(fileName, content);
                
            } catch (Exception e) {
                throw new IOException("文件保存失败!");
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (Exception e) {
                        throw new IOException("文件保存失败!");
                    }
                }
            }
            
            return ossResul;
        }
    }
    

    7、使用阿里云(Service)
    @Service
    public class TestService {

        @Autowired
        private FileUtils fileUtils;
    
        /**
         * 图片上传阿里云
         * @param request
         * @param response
         * @return
         * @throws IOException
         */
    
        public Map<String,Object> upload(HttpServletRequest req){
            Map<String,Object> result = new HashMap<String, Object>();
    
            MultipartHttpServletRequest mReq  =  null;
            MultipartFile file = null;
            InputStream is = null ;
            OSSResultModel ossResult = null;
            String fileName = "";
            // 原始文件名   UEDITOR创建页面元素时的alt和title属性
            String originalFileName = "";
    
            try {
                mReq = (MultipartHttpServletRequest)req;
                // 从config.json中取得上传文件的ID
                file = mReq.getFile("file");
                // 取得文件的原
                fileName = file.getOriginalFilename();
                originalFileName = fileName;
                if(!StringUtils.isEmpty(fileName)){
                    is = file.getInputStream();
                    fileName = fileUtils.reName(fileName);
                    ossResult = fileUtils.saveFile(fileName, is);
                } else {
                    throw new IOException("文件名为空!");
                }
    
                String[] strings = new String[5];
                strings[0] = ossResult.getUrl();
    
    
                result.put("errno",0);
                result.put("data",strings);
    
                //result.put("state", "SUCCESS");// UEDITOR的规则:不为SUCCESS则显示state的内容
                //result.put("url",ossResult.getUrl());
                //result.put("title", fileName);
                //result.put("original", fileName);
            }
            catch (Exception e) {
                System.out.println(e.getMessage());
                result.put("state", "文件上传失败!");
                result.put("url","");
                result.put("title", "");
                result.put("original", "");
                System.out.println("文件 "+fileName+" 上传失败!");
            }
    
            return result;
        }
    
    
    }
    

    8、使用阿里云(Controller)
    @Controller
    public class TestController {

        @Autowired
        TestService testService;
    
         * 图片上传阿里云
         *
         * @param request
         * @param response
         * @return
         * @throws IOException
         */
        @RequestMapping(value = "/upload")
        @ResponseBody
        public Map<String, Object> upload(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            return testService.upload(request);
        }
    
    }
    

    相关文章

      网友评论

        本文标题:spring boot 集成阿里云上传图片

        本文链接:https://www.haomeiwen.com/subject/rlpfeftx.html