|
| 1 | +# 上传图片 & 配置 |
| 2 | + |
| 3 | +将图片上传到服务器上的配置方式 |
| 4 | + |
| 5 | +## 上传图片 |
| 6 | + |
| 7 | +参考如下代码 |
| 8 | + |
| 9 | +```html |
| 10 | +<div id="div1"> |
| 11 | + <p>欢迎使用 wangEditor 富文本编辑器</p> |
| 12 | +</div> |
| 13 | + |
| 14 | +<script type="text/javascript" src="/wangEditor.min.js"></script> |
| 15 | +<script type="text/javascript"> |
| 16 | + var E = window.wangEditor |
| 17 | + var editor = new E('#div1') |
| 18 | +
|
| 19 | + // 配置服务器端地址 |
| 20 | + editor.customConfig.uploadImgServer = '/upload' |
| 21 | +
|
| 22 | + // 进行下文提到的其他配置 |
| 23 | + // …… |
| 24 | + // …… |
| 25 | + // …… |
| 26 | +
|
| 27 | + editor.create() |
| 28 | +</script> |
| 29 | +``` |
| 30 | + |
| 31 | +其中`/upload`是上传图片的服务器端接口,接口返回的**数据格式**如下 |
| 32 | + |
| 33 | +```json |
| 34 | +{ |
| 35 | + // errno 即错误代码,0 表示没有错误。 |
| 36 | + // 如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理 |
| 37 | + errno: 0, |
| 38 | + |
| 39 | + // data 是一个数组,返回若干图片的线上地址 |
| 40 | + data: [ |
| 41 | + '图片1地址', |
| 42 | + '图片2地址', |
| 43 | + '……' |
| 44 | + ] |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +## 限制图片大小 |
| 49 | + |
| 50 | +默认限制图片大小是 5M |
| 51 | + |
| 52 | +```javascript |
| 53 | +// 将图片大小限制为 3M |
| 54 | +editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024 |
| 55 | +``` |
| 56 | + |
| 57 | +## 自定义上传参数 |
| 58 | + |
| 59 | +上传图片时可自定义传递一些参数,例如传递验证的`token`等 |
| 60 | + |
| 61 | +```javascript |
| 62 | +editor.customConfig.uploadImgParams = { |
| 63 | + token: 'abcdef12345' |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +## 自定义 header |
| 68 | + |
| 69 | +上传图片时刻自定义设置 header |
| 70 | + |
| 71 | +```javascript |
| 72 | +editor.customConfig.uploadImgHeaders = { |
| 73 | + 'Accept': 'text/x-json' |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +## withCredentials(跨域传递 cookie) |
| 78 | + |
| 79 | +跨域上传中如果需要传递 cookie 需设置 withCredentials |
| 80 | + |
| 81 | +```javascript |
| 82 | +editor.customConfig.withCredentials = true |
| 83 | +``` |
| 84 | + |
| 85 | +## 自定义 timeout 时间 |
| 86 | + |
| 87 | +默认的 timeout 时间是 5 秒钟 |
| 88 | + |
| 89 | +```javascript |
| 90 | +// 将 timeout 时间改为 3s |
| 91 | +editor.customConfig.uploadImgTimeout = 3000 |
| 92 | +``` |
| 93 | + |
| 94 | +## 监听函数 |
| 95 | + |
| 96 | +可使用监听函数在上传图片的不同阶段做相应处理 |
| 97 | + |
| 98 | +```javascript |
| 99 | +editor.customConfig.uploadImgHooks = { |
| 100 | + before: function (xhr, editor, files) { |
| 101 | + // 请求发送之前 |
| 102 | + }, |
| 103 | + success: function (xhr, editor, result) { |
| 104 | + // 上传成功之后 |
| 105 | + // result 是服务器端返回的结果 |
| 106 | + }, |
| 107 | + fail: function (xhr, editor, result) { |
| 108 | + // 上传失败之后 |
| 109 | + // result 是服务器端返回的结果 |
| 110 | + }, |
| 111 | + error: function (xhr, editor) { |
| 112 | + // 请求发生错误 |
| 113 | + }, |
| 114 | + timeout: function (xhr, editor) { |
| 115 | + // 请求超时 |
| 116 | + } |
| 117 | +} |
| 118 | +``` |
0 commit comments