vue上传图片组件
效果:
vue安装截图插件:
npm install vue-cropper
参考的链接:链接地址
<template>
<div class="footerBtn">
<img v-if="attach.laterUrl" :src="attach.laterUrl" class="preview" style="width:200px;height:200px" />
<!-- 弹出层-裁剪 -->
<el-dialog v-if="dialogVisible" :modal="false" id="userImgDialog" title="编辑头像" :visible.sync="dialogVisible" :before-close="handleClose">
<span>
<el-row>
<input type="file" id="uploads" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event,1)"
class="el-button" style="width: 300px;margin-bottom:15px;">
</el-row>
<el-row :gutter="10">
<el-col :span="14">
<!-- 裁剪 -->
<vueCropper style="width: 300px;height:300px" ref="cropper" :img="attach.customaryUrl" :autoCrop="options.autoCrop"
:fixedBox="options.fixedBox" :canMoveBox="options.canMoveBox" :autoCropWidth="options.autoCropWidth"
:autoCropHeight="options.autoCropHeight" :centerBox="options.centerBox" @realTime="realTime">
</vueCropper>
</el-col>
<el-col :span="10">
<h2 align="center">头像预览</h2>
<div class="show-preview">
<div :style="previews.div" class="preview">
<img :src="previews.url" :style="previews.img">
</div>
</div>
</el-col>
</el-row>
<!-- <el-row class="footerBtn" align="center">
<el-button type="primary" size="small" round="" @click="cut('blob')">确认</el-button>
<el-button type="primary" size="small" round="" @click="handleClose">取消</el-button>
</el-row> -->
</span>
<span slot="footer" class="dialog-footer">
<el-button type="primary" size="small" round="" @click="cut('blob')">确认</el-button>
<el-button type="primary" size="small" round="" @click="handleClose">取消</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import userController from '../../api/UserController.js'
//数据库里需要存两份图片地址,一张为原图地址,一张为裁剪后的头像地址
export default {
data() {
return {
dialogVisible: false,
options: {
autoCrop: true, //默认生成截图框
fixedBox: false, //固定截图框大小
canMoveBox: false, //截图框不能拖动
autoCropWidth: 200, //截图框宽度
autoCropHeight: 200, //截图框高度
centerBox: false, //截图框被限制在图片里面
},
previews: {
div: null,
url: null,
img: null
}, //实时预览图数据
attach: { //后端附件表
user: null,
customaryUrl: '', //原图片路径
laterUrl: '', //裁剪后图片路径 /static/logo.png
attachType: 'photo', //附件类型
}
}
},
mounted() {
//等于当前登录用户
this.attach.user = JSON.parse(window.localStorage.getItem('user'));
},
methods: {
rest(){
this.previews={
div: null,
url: null,
img: null
}; //实时预览图数据
this.attach={ //后端附件表
user: JSON.parse(window.localStorage.getItem('user')),
customaryUrl: '', //原图片路径
laterUrl: '', //裁剪后图片路径 /static/logo.png
attachType: 'photo', //附件类型
};
},
//控制弹出层关闭
handleClose() {
this.dialogVisible = false
},
//实时预览
realTime(data) {
this.previews = data
},
//选择本地图片
uploadImg(e, num) {
var file = e.target.files[0];
if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
this.$message.error('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');
return false;
}
//fileReader 接口,用于异步读取文件数据
var reader = new FileReader();
reader.readAsDataURL(file); //重要 以dataURL形式读取文件
reader.onload = e => {
let data = e.target.result
this.attach.customaryUrl = data
}
},
//确认截图,上传
cut(type) {
if(this.attach.customaryUrl !== '' && this.attach.customaryUrl != null){
var formData = new FormData();
this.$refs.cropper.getCropBlob(res => {
//res是裁剪后图片的bolb对象
formData.append("file", res);
//传到后台进行上传
userController.uploadUserImg(formData).then(v => {
//把当前用户的头像路径改为后台返回的路径
this.attach.user.accountImg = v;
//把修改后的用户信息返回给父类
this.$emit("editUserImg",this.attach.user);
this.dialogVisible = false;
this.$message({
message: '修改成功!',
duration: 2000,
type: 'success'
});
});
})
}else{
this.$message({
message: '请先选择图片!',
duration: 2000,
type: 'warning'
});
}
}
}
}
</script>
<style>
#userImgDialog .el-dialog {
width: 550px;
}
</style>
<style scoped>
/* 弹性布局 水平居中 */
.show-preview {
display: flex;
justify-content: center;
margin-top: 20px;
}
.preview {
border-radius: 50%;
overflow: hidden;
border: 1px solid #cccccc;
background: #cccccc;
}
</style>
**
后台传到七牛云
**
(注册过程自行百度吧 新用户有免费体验的额度 对于个人来说够用啦 需要实名认证才可用)
pom文件导入jar包
<!-- 七牛云 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.7</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6</version>
<!--<scope>compile</scope>-->
</dependency>
建一个工具类
需要的四个重要参数 在七牛云官网自己找哈
accessKey
secretKey
bucketName (空间名 在对象存储)
fileDomain(域名 用的默认的 这个我一开始不知道在哪里 如图)
package com.vwi.utils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* Created by Administrator on 2019/8/15.
*/
@Component
public class QiniuUtils {
//获取方式也自行百度吧
private String accessKey = "you accessKey";//上传凭证AccessKey
private String secretKey = "you secretKey";//上传凭证secretKey
private String bucketName = "存储空间名称";//存储空间名称
private String fileDomain = "http://q9a3g4pb1.bkt.clouddn.com/";//使用的域名 需要改成自己的哦
public String getAccessKey() {
return accessKey;
}
public String getSecretKey() {
return secretKey;
}
public String getBucketName() {
return bucketName;
}
public String getFileDomain() {
return fileDomain;
}
private UploadManager uploadManager;
private BucketManager bucketManager;
private Configuration c;
private Client client;
// 密钥配置
private Auth auth;
public Client getClient(){
if (client==null) {
client=new Client(getConfiguration());
}
return client;
}
public BucketManager getBucketManager() {
if (bucketManager == null) {
bucketManager = new BucketManager(getAuth(), getConfiguration());
}
return bucketManager;
}
public UploadManager getUploadManager() {
if (uploadManager == null) {
uploadManager = new UploadManager(getConfiguration());
}
return uploadManager;
}
public Configuration getConfiguration() {
if (c == null) {
Zone z = Zone.zone2();
c = new Configuration(z);
}
return c;
}
public Auth getAuth() {
if (auth == null) {
auth = Auth.create(getAccessKey(), getSecretKey());
}
return auth;
}
//简单上传模式的凭证
public String getUpToken() {
return getAuth().uploadToken(getBucketName());
}
//覆盖上传模式的凭证
public String getUpToken(String fileKey) {
return getAuth().uploadToken(getBucketName(), fileKey);
}
/**
* 将本地文件上传
* @param filePath 本地文件路径
* @param fileKey 上传到七牛后保存的文件路径名称
* @return String
* @throws IOException
*/
public String upload(String filePath, String fileKey) throws IOException {
Response res;
try {
res = getUploadManager().put(filePath, fileKey, getUpToken(fileKey));
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return fileDomain + "/" + putRet.key;
} catch (QiniuException e) {
res = e.response;
e.printStackTrace();
return "上传失败";
}
}
/**
* 上传二进制数据
* @param data
* @param fileKey
* @return String
* @throws IOException
*/
public String upload(byte[] data, String fileKey) throws IOException {
Response res;
try {
res = getUploadManager().put(data, fileKey, getUpToken(fileKey));
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return fileDomain + "/" + putRet.key;
} catch (QiniuException e) {
res = e.response;
e.printStackTrace();
return "上传失败";
}
}
/**
* 上传输入流
* @param inputStream
* @param fileKey
* @return String
* @throws IOException
*/
public String upload(InputStream inputStream, String fileKey) throws IOException {
Response res;
try {
res = getUploadManager().put(inputStream, fileKey, getUpToken(fileKey),null,null);
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return fileDomain + "/" + putRet.key;
} catch (QiniuException e) {
res = e.response;
e.printStackTrace();
return "上传失败";
}
}
/**
* 删除文件
* @param fileKey
* @return
* @throws QiniuException
*/
public boolean delete(String fileKey) throws QiniuException {
Response response = bucketManager.delete(this.getBucketName(), fileKey);
return response.statusCode == 200 ? true:false;
}
/**
* 获取公共空间文件
* @param fileKey
* @return String
*/
public String getFile(String fileKey) throws Exception{
String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
String url = String.format("%s/%s", fileDomain, encodedFileName);
return url;
}
/**
* 获取私有空间文件
* @param fileKey
* @return String
*/
public String getPrivateFile(String fileKey) throws Exception{
String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
String url = String.format("%s/%s", fileDomain, encodedFileName);
Auth auth = Auth.create(accessKey, secretKey);
long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
String finalUrl = auth.privateDownloadUrl(url, expireInSeconds);
return finalUrl;
}
}
Controller调用
@RestController
public class UserController {
@Autowired
QiniuUtils qiniuUtils;
/**
* 上传头像
* @param file
* @throws IllegalStateException
* @throws IOException
*/
@RequestMapping("/uploadUserImg")
public String uploadUserImg(@RequestParam MultipartFile file) throws IllegalStateException, IOException{
if (!file.isEmpty()) {
FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
//默认不指定key的情况下,以文件内容的hash值作为文件名
String fileKey = UUID.randomUUID()+ ".png";
return qiniuUtils.upload(fileInputStream,fileKey);
}
return "上传失败";
}
}
跟着步骤来很容易就完成啦 但是我自己却是捣鼓了半天才完成的 记录一下吧