1.maven依赖
<!--七牛-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.8</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
2.config.properties配置文件中配置七牛云的信息:
qiniu.ak=BJSh2yr7jNedBVryDw6mZ-a9frqfp_LRUD2U1T
qiniu.sk=MgKmnIrj9arez2ZQMMrz2H0us4GFbq4a1gnFaaqQ
qiniu.buket=java25
3.SpringMVC的配置文件xxx-servlet中配置文件上传解析器
前端form表单添加enctype="multipart/form-data"属性:
后端Controller:
4.业务层读取七牛云的配置文件信息:
@Value("${qiniu.ak}")
private String qiniuAk;
@Value("${qiniu.sk}")
private String qiniuSk;
@Value("${qiniu.buket}")
private String qiniuBuket;
将图片上传到七牛云:
@Transactional
public void saveProduct(Product product, InputStream inputStream) {
//上传文件到七牛云
Configuration configuration = new Configuration(Zone.zone1());
UploadManager uploadManager = new UploadManager(configuration);
Auth auth = Auth.create(qiniuAk,qiniuSk);
String uploadToken = auth.uploadToken(qiniuBuket);
String key = null;
try {
Response response = uploadManager.put(IOUtils.toByteArray(inputStream),null,uploadToken);
DefaultPutRet defaultPutRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
key = defaultPutRet.key;
} catch (IOException e) {
throw new RuntimeException("上传文件到七牛异常",e);
}
//保存对象
product.setProductImg(key);
productMapper.insertSelective(product);
}
5.在前端页面使用img标签来显示图片:
<img src="http://ozp5bpxi8.bkt.clouddn.com/${product.productImg}?imageView2/1/w/200/h/200" >