easyui上传图片到腾讯云OSS并且显示出来(☆)

本文介绍了一种使用腾讯云对象存储服务OOS进行图片上传的方法,详细讲解了从前端页面设计到后端控制器、服务层实现及工具类使用的全过程。通过HTML表单收集图片,利用JavaScript进行表单提交,后端采用Spring MVC接收并处理图片数据,最终调用TencentOssUtil工具类完成图片上传至OOS。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html代码

<form  id="ff" method="post" action="${path}/ebayKanDeng/draft/<#if ebayItem??>update<#else>add</#if>">
       
        <input type="hidden" name="id" value="${ebayItem.id}"  enctype="multipart/form-data">
           
        <div class="fr">
            <label>典型图片</label>
            <input class="easyui-filebox"  style="width:380px;height:40px;"  multiple name="img" id="image"/>     
        </div>
    </form>
    
    <div style="text-align:left;padding:5px">
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="submitForm()">确认添加</a>&nbsp; &nbsp; &nbsp; &nbsp;
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="clearForm()">清空</a>
    </div>

js代码

  /* 
     下面上传图片的代码
    */
    
    function submitForm(){
    	
        $("#ff").form('submit', {
            type:"post",  //提交方式
            data:$('#ff').serialize(),
            dataType: 'json',
            url:'${path}/ebayKanDeng/draft/addImgToOos', //请求url
            success:function(map)
            {
            
                map = eval( '('+map+')' );      //form形式提交,就收后台数据需要再转换
                //alert("map.result.msg="+map.result.msg);
                if(map.result.msg == 1)
                {
                    $.messager.alert("操作提示","保存信息成功");
                }
                else{
                    $.messager.alert("操作提示","保存信息失败");
                }

            }
        });
    }

    function clearForm(){
        $('#ff').form('clear');
    }

controller代码


	    /**
	     * 上传到腾讯云oos
	     * @param ebayItem
	     * @param img
	     * @param request
	     * @return
	     */
	    @RequestMapping(method=RequestMethod.POST,value="addImgToOos")
	    @ResponseBody
	    public Map<String,Object> addImgToOos(EbayItem ebayItem, @RequestParam(value="img",required = false)
	    MultipartFile[] img,HttpServletRequest request){
	    
	    if(ebayItem.getId()==null) {
	    	throw new MyBusinessException("缺少商品id");
	    }
	   
	    Map<String ,Object> map=new LinkedHashMap<>();
	  
	    try {
              
	        //将数据保存
	        ebayItemSerivice.saveImgToOos(ebayItem,img);
	        map.put("msg","1");
	        return map;
	    } catch (Exception e){
	        e.printStackTrace();
	        map.put("msg",e.getMessage());
	    }
	    return map;
	}
	    

service代码

 void saveImgToOos(EbayItem ebayItem,MultipartFile[] files);

service实现代码

@Override
	public void saveImgToOos(EbayItem ebayItem,MultipartFile[] files) {
		// TODO Auto-generated method stub
		//多图片路径
		List<MultipartFile> muls=new ArrayList();
		for (MultipartFile s : files) {
			muls.add(s);
		}
		
		String imgurl=tencentOssUtil.checkList(muls);
		
	    ebayItem.setImgPath(imgurl);
	    ebayItemDao.updateByPrimaryKeySelective(ebayItem);
	    log.info(imgurl);
	    if(StringUtil.isEmpty(ebayItem.getImgPath())) {
	    	throw new MyBusinessException("添加图片失败");
	    }
	    log.info(imgurl);
		
	}

工具类

package com.iautorun.lepower.service.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
@Component
public class TencentOssUtil {
	
	protected static final Logger log = LoggerFactory.getLogger(TencentOssUtil.class);
	
	    @Value("${Oos.SecretId}")
	    private String secretId;
	    @Value("${Oos.SecretKey}")
	    private String secretKey;
	    @Value("${Oos.region}")
	    private String region;
	    @Value("${Oos.bucketName}")
	    private String bucketName;
	    @Value("${Oos.AppId}")
	    private String appId;
	    
	    
	    
	    public  String picCOS(MultipartFile cosFile) throws Exception {
			
			COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
			// 2 设置bucket的区域, COS地域的简称请参照
			// https://cloud.tencent.com/document/product/436/6224
			ClientConfig clientConfig = new ClientConfig(new Region(region));
			// 3 生成cos客户端
			COSClient cosClient = new COSClient(cred, clientConfig);
			String bucketNameNew = bucketName;
			String key = "image/"+new Date().getTime() + ".png";
			// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
			// 大文件上传请参照 API 文档高级 API 上传
			// 指定要上传到 COS 上的路径
	        File toFile=null;
	        InputStream ins = null;
            ins = cosFile.getInputStream();
            toFile = new File(cosFile.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
             
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketNameNew, key, toFile);
			cosClient.putObject(putObjectRequest);
			cosClient.shutdown();
			 Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
			URL url = cosClient.generatePresignedUrl(bucketNameNew, key, expiration);
			String urlNew=url.toString();
			int begin=urlNew.indexOf("?");
			String urlNewest="";
            if(begin==-1) {
            	 return urlNewest;
            }else {
            	urlNewest=urlNew.substring(0, begin);
            	return urlNewest;
            }
			
		}
	    
	    
	    private static void inputStreamToFile(InputStream ins, File file) {
	        try {
	            OutputStream os = new FileOutputStream(file);
	            int bytesRead = 0;
	            byte[] buffer = new byte[8192];
	            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
	                os.write(buffer, 0, bytesRead);
	            }
	            os.close();
	            ins.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    
	    
	    
	    public String checkList(List<MultipartFile> fileList) {
	       
	        String  str = "";
	        String  photoUrl = "";
	        for(int i = 0;i< fileList.size();i++){
	           
	            try {
					str = picCOS(fileList.get(i));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            if(i == 0){
	                photoUrl = str;
	            }else {
	                photoUrl += "," + str;
	            }
	        }
	        return photoUrl.trim();
	    } 


}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

playboy-jordan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值