关于上传图片到七牛云的步骤以及redis缓存图片名称

1.关于上传图片到七牛云的步骤

1.1前端代码

1.1.1 html组件

<el-form-item label="上传图片">
   <el-upload
           class="avatar-uploader"
           action="/setmeal/upload.do"
           :auto-upload="autoUpload"
           name="imgFile"
           :show-file-list="false"
           :on-success="handleAvatarSuccess"
           :before-upload="beforeAvatarUpload">
           <!--    action="/setmeal/upload.do"     向后端发送的请求--> 
           <!--    action="/setmeal/upload.do"     向后端发送的请求--> 
      	   <!--    name="imgFile" 				   携带的参数-->
      	   <!--    :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>
</el-form-item>

1.1.2 vue函数代码

//文件上传成功后的钩子,response为服务端返回的值,file为当前上传的文件封装成的js对象
                handleAvatarSuccess(response, file) {
                    // 对imageUrl赋值,将图片显示到文件上传的框中,进行浏览
                    this.imageUrl = "http://r769i4ffc.hn-bkt.clouddn.com/"+response.data; // 用于显示
                    this.$message({
                        message: response.message,
                        type: response.flag ? 'success' : 'error'
                    });
                    //设置模型数据(图片名称),后续提交ajax请求时会提交到后台最终保存到数据库
                    this.formData.img = response.data; // 用于保存
                },
                //上传图片之前执行
                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;
                }

1.2后端代码

1.2.1处理请求类


    // imgFile:需要跟页面el-upload里面的name保持一致
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            // 找到.最后出现的位置
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf);
            //使用UUID随机产生文件名称,防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            //七牛云里面上传数据
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //图片上传成功
            Result result = new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
    }

1.2.1七牛云的工具工具类

/**
 * @author Zhang
 * @create 2022/2/18 20:02
 */
public class QiniuUtils {
	//七牛云密钥
    public  static String accessKey = "xxxxxxxxxxxxxxxx";
    public  static String secretKey = "xxxxxxxxxxxxxxxx";
    //项目名称
    public  static String bucket = "xxxxxxxxxxxxxxxxxxx";

    public static void upload2Qiniu(String filePath,String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //上传文件
    public static void upload2Qiniu(byte[] bytes, String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName){
        //构造一个带指定Zone对象的配置类
        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());
        }
    }

}

2.关于上传图片到七牛云的步骤

2.1后端代码

@Reference
    private SetmealService setmealService;

    // imgFile:需要跟页面el-upload里面的name保持一致
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            // 找到.最后出现的位置
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf);
            //使用UUID随机产生文件名称,防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            //七牛云里面上传数据
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //做一个缓存将存到七牛云的照片存入到redis数据库中作为缓存
            setmealService.savePicAllRedis(fileName);
            //图片上传成功
            Result result = new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

service模块

    public void savePicAllRedis(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,pic);
    }

常量类

public class RedisConstant {
    //套餐图片所有图片名称(七牛)
    public static final String SETMEAL_PIC_RESOURCES = "setmealPicResources";
    //套餐图片保存在数据库中的图片名称(数据库)
    public static final String SETMEAL_PIC_DB_RESOURCES = "setmealPicDbResources";
}

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                         http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/mvc
                         http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://code.alibabatech.com/schema/dubbo
                         http://code.alibabatech.com/schema/dubbo/dubbo.xsd
                        http://www.springframework.org/schema/context
                         http://www.springframework.org/schema/context/spring-context.xsd">

    <!--Jedis连接池的相关配置-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal">
            <value>200</value>
        </property>
        <property name="maxIdle">
            <value>50</value>
        </property>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
    </bean>
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
        <constructor-arg name="host" value="192.168.80.100" />
        <constructor-arg name="port" value="6379" type="int" />
        <constructor-arg name="timeout" value="30000" type="int" />
    </bean>
</beans>

3. 关于上传图片确定后的执行流程

3.1 后端代码

controller

//新增"/setmeal/add.do?travelGroupIds="
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] travelGroupIds){
        try {
            setmealService.add(setmeal,travelGroupIds);
            //新增套餐成功
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e){
            //新增套餐失败
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

service

 @Autowired
    private JedisPool jedisPool;

    //新增套餐
    public void add(Setmeal setmeal, Integer[] travelgroupIds) {
        setmealDao.add(setmeal);
        if(travelgroupIds != null && travelgroupIds.length > 0){
            //绑定套餐和跟团游的多对多关系
            setSetmealAndTravelGroup(setmeal.getId(),travelgroupIds);
        }
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
    }
    //将图片名称保存到Redis
    private void savePic2Redis(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }

dao

    <!--新增-->
    <insert id="add" parameterType="setmeal">
        <selectKey resultType="int" order="AFTER" keyProperty="id">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into t_setmeal(name,code,helpCode,sex,age,price,remark,attention,img) values (#{name},#{code},#{helpCode},#{sex},#{age},#{price},#{remark},#{attention},#{img})
    </insert>




    <!--绑定套餐和跟团游多对多关系-->
    <insert id="setSetmealAndTravelGroup" parameterType="map">
        insert into t_setmeal_travelgroup(setmeal_id,travelgroup_id) values (#{setmeal_id},#{travelgroup_id})
    </insert>

3.2 前端代码

                //添加
                handleAdd () {
                    axios.post("/setmeal/add.do?travelGroupIds=" + this.travelgroupIds,this.formData).then((response)=> {
                        this.dialogFormVisible = false;
                        if(response.data.flag){
                            this.$message.success(response.data.message);
                        }else{
                            this.$message.error(response.data.message);
                        }
                    }).finally(()=> {
                        this.findPage();
                    });
                },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值