文章目录
springboot中将图片存储到七牛云上
文章目录
- 文章目录
- 一、导入七牛云依赖包
- 二、在utils中添加两个工具类
- 1.QiniuUtils类
- 2.PictureUtil类
- 三、一个前端页面用于提交上传的图片
- 四、在controller中添加上传图片的TestQiNiuController
一、导入七牛云依赖包
在项目中直接用maven进行添加依赖
在pom.xml中引入依赖
<!--java 整合七牛云 依赖包-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
<!--七牛需要用到此依赖-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
二、在utils中添加两个工具类
1.QiniuUtils类
QiniuUtils类用作连接存储空间,并上传图片。
这里需要填的有AK和SK在个人中心处密钥管理中查看即可。
BUCKETNAME 是空间名称,在空间管理中查看即可。
DOMAIN 是链接域名,在对个人的云储存空间设置域名后,填充即可。
QiniuUtils类用于上传图片的具体代码
代码如下(示例):
package com.zxxx.lsw.util;
/**
* @author
* @date 2021 / 12 / 11 17: 03
* @version 3.0
*/
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.io.FileInputStream;
import lombok.extern.slf4j.Slf4j;
import com.google.gson.Gson;
@Slf4j
public class QiniuUtils {
// 设置需要操作的账号的AK和SK
private static final String ACCESS_KEY = "XXXXXX";
private static final String SECRET_KEY = "XXXXXX";
// 要上传的空间名称
private static final String BUCKETNAME = "XXXXXX";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
// 外链默认域名
private static final String DOMAIN = "XXXXXX";
/**
* 将图片上传到七牛云
*/
public static String uploadQNImg(FileInputStream file, String key) {
// 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
Configuration cfg = new Configuration(Zone.zone2());
// 其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
// 生成上传凭证,然后准备上传
try {
// Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(BUCKETNAME);
try {
Response response = uploadManager.put(file, key, upToken, null, null);
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
String returnPath = DOMAIN + "/" + putRet.key;
// 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
return returnPath;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
2.PictureUtil类
PictureUtil类用于生成一个随机字符串(代码中名称为sb),该串作为存储文件的名字。
图片存储url为:DOMAIN + sb
PictureUtil代码如下:
package com.zxxx.lsw.util;
/**
* show
* @author
* @date 2021 / 12 / 11 16: 52
* param
* @return 具体看框架生成的方法
* @version 3.0
* */
import java.util.Random;
public class PictureUtil {
public static String getRandomFileName(){
//随机生成一个字符串
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<10;i++){
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
}
三、一个前端页面用于提交上传的图片
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/testUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">上传</button>
</form>
</body>
</html>
四、在controller中添加上传图片的TestQiNiuController
package com.zxxx.lsw.controller;
/**
* @author
* @date 2021 / 12 / 11 16: 53
* @version 3.0
*/
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxxx.lsw.mapper.*;
import com.zxxx.lsw.pojo.*;
import com.zxxx.lsw.util.QiniuUtils;
import com.zxxx.lsw.util.PictureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("/developer/contract")
public class TestQiNiuController {
@Autowired
private SalerMapper salerMapper;
@Autowired
private CommunityMapper communityMapper;
@Autowired
private AreaMapper areaMapper;
@Autowired
private ViewParkingInfoMapper viewParkingInfoMapper;
@Autowired
private InvoicecontractMapper invoicecontractMapper;
@Autowired
private ParkingMapper parkingMapper;
@RequestMapping("/toIndex")
public String index(){
return "img";
}
@ResponseBody
@RequestMapping(value = "/image", method = RequestMethod.POST)
private String postContractUpDate(HttpServletRequest request,
@RequestParam("Pno") String Pno,
@RequestParam("file") MultipartFile multipartFile,
Model model, HttpSession session) throws IOException {
Developer developer = (Developer)session.getAttribute("user");
System.out.println("Pno:"+Pno);
// 用来获取其他参数
MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
String name = params.getParameter("username");
if (!multipartFile.isEmpty()) {
FileInputStream inputStream = null;
try {
inputStream = (FileInputStream) multipartFile.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String path = QiniuUtils.uploadQNImg(inputStream, PictureUtil.getRandomFileName());
// KeyUtil.genUniqueKey()生成图片的随机名
System.out.print("七牛云返回的图片链接:" + path);
//ICno 逻辑处理操作
int maxicno = 0;
List<Invoicecontract> invoicecontracts = invoicecontractMapper.selectList(null);
for(Invoicecontract invoicecontract : invoicecontracts){
if(invoicecontract.getPno().equals(Pno))maxicno = invoicecontract.getICno();
}
// 在数据库中 存储path
// 以下为个人项目需要的数据处理,读者可不看
Invoicecontract contract = new Invoicecontract();
contract.setICno(maxicno);
contract.setContract(path);
contract.setPno(Pno);
QueryWrapper<Invoicecontract> queryWrapper2 = new QueryWrapper<>();
queryWrapper2.eq("ICno",contract.getICno());
if (invoicecontractMapper.update(contract,queryWrapper2) > 0){
System.out.println("contract更新成功!");
}
// 更新parking标记
Parking park = new Parking();
park.setPno(Pno);
park.setPcontract("1");
QueryWrapper<Parking> queryWrapper3 = new QueryWrapper<>();
queryWrapper3.eq("Pno",park.getPno());
if (parkingMapper.update(park,queryWrapper3) > 0){
System.out.println("parking更新成功!");
}
QueryWrapper<ViewParkingInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("Dno",developer.getDno());
List<ViewParkingInfo> viewParkingInfos = viewParkingInfoMapper.selectList(queryWrapper);
for(ViewParkingInfo viewParkingInfo : viewParkingInfos){
if(viewParkingInfo.getPstatus().equals("0"))viewParkingInfo.setPstatus("可售");
else if(viewParkingInfo.getPstatus().equals("1"))viewParkingInfo.setPstatus("已预约");
else if(viewParkingInfo.getPstatus().equals("2"))viewParkingInfo.setPstatus("已出售");
}
List<Community> communities = communityMapper.selectList(null);
List<Area> areas = areaMapper.selectList(null);
List<Saler> salers = salerMapper.selectList(null);
List<ViewParkingInfo> parkingContoact = new ArrayList<>();
List<ViewParkingInfo> noParkingContoact = new ArrayList<>();
for (ViewParkingInfo viewParkingInfo : viewParkingInfos){
if(viewParkingInfo.getPcontract().equals("1"))parkingContoact.add(viewParkingInfo);
else if(viewParkingInfo.getPinvoice().equals("0"))noParkingContoact.add(viewParkingInfo);
}
model.addAttribute("parkingContracts",parkingContoact);
model.addAttribute("noParkingContracts",noParkingContoact);
model.addAttribute("communities",communities);
model.addAttribute("areas",areas);
model.addAttribute("salers",salers);
return "developer/contract";
}
return "developer/contract";
}
}