七牛云配置图片存储服务器


YL     2022-03-06     271

七牛云配置图片存储服务器

目录

注册账号之后 实名认证

此处不再演示

进入控制台,新建空间

image-20220306134205745

image-20220306134828074

获取AK 和SK

image-20220306134341921

image-20220306134417608

测试域名

image-20220306135354343

新建Springboot项目 引入依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.79</version>
        </dependency>

        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.9.3</version>
        </dependency>

配置图片上传Utils

public class FileUtil {
	// 图片允许的后缀扩展名
	public static String[] IMAGE_FILE_EXTD = new String[] { "png", "bmp", "jpg", "jpeg","pdf" };

	public static boolean isFileAllowed(String fileName) {
		for (String ext : IMAGE_FILE_EXTD) {
			if (ext.equals(fileName)) {
				return true;
			}
		}
		return false;
	}
}

配置七牛云存储Service

import com.alibaba.fastjson.JSONObject;
import com.example.Utils.FileUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

@Service
public class QiniuService {
	private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

	// 设置好账号的ACCESS_KEY和SECRET_KEY
	String ACCESS_KEY = "######################";
	String SECRET_KEY = "######################";
	// 要上传的空间
	String bucketname = "#####";

	// 密钥配置
	Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	// 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
//	Region region = new RegionGroup();
	Configuration cfg = new Configuration(Region.autoRegion());
	// ...其他参数参考类注释
	UploadManager uploadManager = new UploadManager(cfg);

	// 测试域名,只有30天有效期
	private static String QINIU_IMAGE_DOMAIN = "http://###############/";

	// 简单上传,使用默认策略,只需要设置上传的空间名就可以了
	public String getUpToken() {
		return auth.uploadToken(bucketname);
	}

	public String saveImage(MultipartFile file) throws IOException {
		try {
			int dotPos = file.getOriginalFilename().lastIndexOf(".");
			if (dotPos < 0) {
				return null;
			}
			String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
			// 判断是否是合法的文件后缀
			if (!FileUtil.isFileAllowed(fileExt)) {
				return null;
			}
			String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
			// 调用put方法上传
			Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
			// 打印返回的信息
			if (res.isOK() && res.isJson()) {
				// 返回这张存储照片的地址
				return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
			} else {
				logger.error("七牛异常:" + res.bodyString());
				return null;
			}
		} catch (QiniuException e) {
			// 请求失败时打印的异常的信息
			logger.error("七牛异常:" + e.getMessage());
			return null;
		}
	}
}

需要填的地方我都用#########标注了

新建HTML 上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/testUpload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit">上传</button>
</form>

</body>
</html>

配置静态资源过滤和Springboot启动端口

server:
  port: 8080

spring:
  mvc:
    static-path-pattern: /**
  web:
    resources:
      static-locations: classpath:/templates/,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

最后是Controller

import com.example.Service.QiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
public class TestController {
	@Autowired
	private QiniuService qiniuService;

	@RequestMapping(value = "/testUpload", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		if(file.isEmpty()) {
			return "error";
		}
		try {
			String fileUrl=qiniuService.saveImage(file);
			return "success, imageUrl = " + fileUrl;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "fail";
	}
}

打开http://localhost:8080/upload.html 选择文件上传

文件上传成功 可以用链接直接访问了

image-20220306135514348

image-20220306135550577

在文件管理也能看到已上传的图片

image-20220306135711016