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>
<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();
}
}