我也不是专业的前端,就是全部靠百度来的,完成了图片拖拽上传以及调整大小
安装
npm install vue-quill-editor --save
配置
main.js
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
.vue
<quill-editor
v-model="content"
ref="myQuillEditor"
:options="editorOption"
> </quill-editor>
添加拖拽上传图片,以及上传后显示
npm install quill-image-extend-module --save-dev
.vue引入
import VueQuillEditor, { Quill } from 'vue-quill-editor'
import { ImageDrop } from 'quill-image-drop-module'
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', ImageResize)
data
editorOption: {
// 富文本框配置
placeholder: '',
theme: 'snow',// or 'bubble'
modules:{
toolbar:{
container: [
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }],
[{ 'indent': '-1' }, { 'indent': '+1' }], [{ 'direction': 'rtl' }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'font': [] }], [{ 'color': [] }, { 'background': [] }],
[{ 'align': [] }],
['clean'],
['link', 'image', 'video']
], // 工具栏
handlers: { }
},
history: {
delay: 1000,
maxStack: 50,
userOnly: false
},
imageDrop: true,//这个是重点
imageResize: {
displayStyles: {
backgroundColor: 'black',
border: 'none',
color: 'white'
},
modules: ['Resize', 'DisplaySize', 'Toolbar' ]
}
}
}
运行时报 imports 错误 vue.config.js
configureWebpack: config => {
var quillImage = new webpack.ProvidePlugin(
{
'window.Quill': 'quill/dist/quill.js',
'Quill': 'quill/dist/quill.js'
})
config.plugins.push(quillImage);
},
默认上传是beas64
变成自己的上传图片
其实就是把富文本框默认点击事件变成自己的upload的点击事件
第一步写一个上传图片我用的是ant design vue中的upload
<div style="display: none">
<a-upload showUploadList="false" :customRequest="customRequest" > </a-upload>
</div>
在create中方法调用 setHandlers 不用this的可以直接在data中声明
setHandlers(){
var that=this;
this.editorOption.modules.toolbar.handlers={
'image': function(value) {
if (value) {
document.querySelector('#iviwUp input').click()
} else {
that.quill.format('image', false);
}
}
}
对于 ant design vue中的upload自定义事件
customRequest (data) {
const formData = new FormData()
formData.append('image', data.file)
// formData.append('token', 'aiufpaidfupipiu')//随便写一个token示例 this.saveFile(formData)
},
saveFile (formData) {
let that = this let
quill = this.$refs.myQuillEditor.quill
httpAction('/uploadImg', formData, 'post').then((res) => {
if (res.success) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片 res.info为服务器返回的图片地址
quill.insertEmbed(length, 'image',res.result)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
that.$message.warning(res.message);
}
})
}
后台
pom.xml
<!--七牛-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.1.1</version>
</dependency>
新建工具类QiNiuUtil
public class QiNiuUtil {
// 设置需要操作的账号的AK和SK
private static final StringACCESS_KEY ="";
private static final StringSECRET_KEY ="";
// 要上传的空间
private static final Stringbucketname ="";
// 密钥
private static final Authauth = Auth.create(ACCESS_KEY,SECRET_KEY);
private static final StringDOMAIN ="";
private static final Stringstyle ="自定义的图片样式";
public String getUpToken() {
return auth.uploadToken(bucketname,null,3600,new StringMap().put("insertOnly",1));
}
// 普通上传
public String upload(String filePath, String fileName)throws IOException {
// 创建上传对象
UploadManager uploadManager =new UploadManager();
try {
// 调用put方法上传
String token =auth.uploadToken(bucketname);
if(StringUtils.isEmpty(token)) {
System.out.println("未获取到token,请重试!");
return null;
}
Response res = uploadManager.put(filePath, fileName, token);
// 打印返回的信息
System.out.println(res.bodyString());
if (res.isOK()) {
Ret ret = res.jsonToObject(Ret.class);
//如果不需要对图片进行样式处理,则使用以下方式即可
return DOMAIN + ret.key;
// return DOMAIN + ret.key + "?" + style;
}
}catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
// 响应的文本信息
System.out.println(r.bodyString());
}catch (QiniuException e1) {
// ignore
}
}
return null;
}
//base64方式上传
public String put64image(byte[] base64, String key)throws Exception{
String file64 = Base64.encodeToString(base64,0);
Integer l = base64.length;
String url ="http://upload.qiniu.com/putb64/" + l +"/key/"+ UrlSafeBase64.encodeToString(key);
//非华东空间需要根据注意事项 1 修改上传域名 这个是重点当初手贱选的别的然后一直出不来
RequestBody rb = RequestBody.create(null, file64);
Request request =new Request.Builder().
url(url).
addHeader("Content-Type","application/octet-stream")
. addHeader("Authorization","UpToken " + getUpToken())
.post(rb).build();
//System.out.println(request.headers());
OkHttpClient client =new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
System.out.println(response);
//如果不需要添加图片样式,使用以下方式
return DOMAIN + key;
// return DOMAIN + key + "?" + style;
}
// 普通删除(暂未使用以下方法,未测试)
public void delete(String key)throws IOException {
// 实例化一个BucketManager对象
BucketManager bucketManager =new BucketManager(auth);
// 此处的33是去掉:http://ongsua0j7.bkt.clouddn.com/,剩下的key就是图片在七牛云的名称
key = key.substring(33);
try {
// 调用delete方法移动文件
bucketManager.delete(bucketname, key);
}catch (QiniuException e) {
// 捕获异常信息
Response r = e.response;
System.out.println(r.toString());
}
}
class Ret {
public long fsize;
public Stringkey;
public Stringhash;
public int width;
public int height;
}
}
StringACCESS_KEY
StringSECRET_KEY
Stringbucketname
StringDOMAIN
填什么
自己百度
public Result uploadImg(@RequestParam MultipartFile image, HttpServletRequest request) {
Result result =new Result();
if (image.isEmpty()) {
result.setCode(400);
result.setMessage("文件为空,请重新上传");
return result;
}
try {
byte[] bytes = image.getBytes();
String imageName = UUID.randomUUID().toString();
QiNiuUtil qiniuUtil =new QiNiuUtil();
try {
//使用base64方式上传到七牛云
String url = qiniuUtil.put64image(bytes, imageName);
result.setCode(200);
result.setMessage("文件上传成功");
result.setResult(url);
}catch (Exception e) {
e.printStackTrace();
}
return result;
}catch (IOException e) {
result.setCode(500);
result.setMessage("文件上传发生异常!");
return result;
}
}