spring boot 图片上传阿里云oss云存储

上传阿里云工具类:

package com.example.demo.common;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
/**
 * Created by Administrator on 2018/1/27 0027.
 */
public class OSSClientUtil {
    Log log = LogFactory.getLog(OSSClientUtil.class);
    // endpoint以杭州为例,其它region请按实际情况填写
    protected static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    protected static String accessKeyId  = "你的accessKeyId";
    protected static String accessKeySecret  = "你的accessKeySecret";
    protected static String bucketName  = "weishang-fc";
    //文件存储目录
    private String filedir = "imgupload/";

    private OSSClient ossClient;

    public OSSClientUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) throws Exception {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new Exception("图片上传失败01");
        }
    }


    public String uploadImg2Oss(MultipartFile file) throws Exception {
        if (file.getSize() > 1024 * 1024) {
            throw new Exception("上传图片大小不能超过1M!");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            throw new Exception("图片上传失败02");
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
}

service:(这个根据需要,也可以省略直接在controller里面写)

@Service
public class UpDownServiceImpl {

    private OSSClientUtil ossClient=new OSSClientUtil();
    public String updateHead(MultipartFile file, long userId) throws Exception {
        if (file == null || file.getSize() <= 0) {
            throw new Exception("头像不能为空");
        }
        String name = ossClient.uploadImg2Oss(file);
        String imgUrl = ossClient.getImgUrl(name);
        //userDao.updateHead(userId, imgUrl);//只是本地上传使用的
        return imgUrl;
    }
}

controller:

@Controller
@RequestMapping("/user")
public class UserController {

//处理文件上传
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    @ResponseBody
    /*public  String uploadImg(@RequestParam("file") MultipartFile file,
                             HttpServletRequest request) {*/
        public Map<String, Object> headImgUpload(HttpServletRequest request,@RequestParam("file")MultipartFile file) {
            Map<String, Object> value = new HashMap<String, Object>();
            value.put("success", true);
            value.put("errorCode", 0);
            value.put("errorMsg", "");
            try {
                String head = upDownServiceImpl.updateHead(file, 4);//此处是调用上传服务接口,4是需要更新的userId 测试数据。
                value.put("data", head);
            } catch (IOException e) {
                e.printStackTrace();
                value.put("success", false);
                value.put("errorCode", 200);
                value.put("errorMsg", "图片上传失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
        return value; 
    }
}

前端页面:

<!--文件上传-->
        <div style="border: solid 1px">
            <form enctype="multipart/form-data" method="post" th:action= "@{/user/testuploadimg}">
                图片<input type="file" name="file"/>
                <input type="submit" value="上传"/>
            </form>
        </div>

我自己捣鼓了半天的小坑:
bucket.oss-cn-hangzhou.aliyuncs.com 不要填类似这样的
应该直接填Endpoint,如:
oss-cn-shanghai.aliyuncs.com
我一直写成:

// endpoint以杭州为例,其它region请按实际情况填写
    protected static String endpoint = "http://weishang-fc.oss-cn-shanghai.aliyuncs.com";
    protected static String accessKeyId  = "xx";
    protected static String accessKeySecret  = "xx";
    protected static String bucketName  = "weishang-fc"; 

正确应该是这样:

   // endpoint以杭州为例,其它region请按实际情况填写
    protected static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    protected static String accessKeyId  = "xx";
    protected static String accessKeySecret  = "xx";
    protected static String bucketName  = "weishang-fc"; 

这里只是简单的单个图片/文件的上传,记录下来,方便下次使用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值