eleui 图片上传至七牛云服务器

4 篇文章 0 订阅
1 篇文章 0 订阅

前端页面(elementui)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
<div id="app">
    <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/setMeal/upload"
            :auto-upload="autoUpload"
            name="imgFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                imageUrl: ''
            };
        },
        methods: {
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        }
    })
</script>
</html>

后端

maven坐标:

<!-- 上传工具 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!--七牛云-->
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.2.0</version>
</dependency>

在spring-mvc.xml配置文件中配置上传解析器

<!--    配置文件上传解析器-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
    <property value="104857600" name="maxUploadSize"/>
    <property value="4096" name="maxInMemorySize"/>
    <property value="UTF-8" name="defaultEncoding"/>
</bean>

controllerweb层:

/**
 * 文件上传
 *
 * @return
 */
@RequestMapping("upload")
public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
    try {
        //原文件名
        String filename = imgFile.getOriginalFilename();
        //uuid生成随机图片名防止图片重名,把所有的"-"替换成掉,在加上原图片名
        String savFileName = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
        //使用自定义七牛工具类
        QiniuUtils.upload2Qiniu(imgFile.getBytes(), savFileName);
        //上传后在把图片名保存到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, savFileName);
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, QiniuUtils.qiniu_img_url_pre + savFileName);
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }
}

七牛工具类:

public class QiniuUtils {
    public static String qiniu_img_url_pre = "http://qdn8v47w0.bkt.clouddn.com/";
    public static String accessKey = "M8AHxRBhBw7Hkmsc1NfdTZpT4ZZA5WE1t000OI51";
    public static String secretKey = "-ahel4qCJgVaQvf6LggHtBK5xlYtIY7JNast21Ck";
    public static String bucket = "health-test-0";

    /**
     * 上传文件
     *
     * @param bytes          文件内容,字节数组
     * @param uploadFileName 保存到服务端的文件名
     */
    public static void upload2Qiniu(byte[] bytes, String uploadFileName) {
        //构造一个带指定Zone对象的配置类  zone2():华南地区
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = uploadFileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            System.out.println(response.bodyString());
            // 访问路径
            System.out.println("http://qdn8v47w0.bkt.clouddn.com/" + uploadFileName);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                ex.printStackTrace();
            }
        }
    }
    /**
     * 删除文件
     *
     * @param fileName 服务端文件名
     */
    public static void deleteFileFromQiniu(String fileName) {
        //构造一个带指定Zone对象的配置类  zone2():华南地区
        Configuration cfg = new Configuration(Zone.zone2());
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常,说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

   
  
    public static void main(String args[]) throws IOException {
        // 测试上传
        String localFilePath = "C:\\Users\\Administrator\\Desktop\\test.jpg";
        FileInputStream fileInputStream = new FileInputStream(localFilePath);
        byte[] data = new byte[1024 * 1024];
        fileInputStream.read(data);
        String saveFileName = UUID.randomUUID().toString().replace("-", "");
        QiniuUtils.upload2Qiniu(data, saveFileName);
        // 测试删除
        deleteFileFromQiniu("19573c9b8ace4f939c658e7249215f9b_test.jpg");
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值