OSS上传图片无法在线预览的解决方案


最近在做的项目涉及到商品详情,由于前端用的flutter框架并且该详情为富文本,dart语言关于富文本的组件不是非常友好,当富文本中的图片无法在浏览器中直接预览的时候(有时提示为下载链接),富文本组件无法显示。


先记录一下踩过的坑: 富文本中的图片也需要相应的服务器进行存储,否则会直接转化成十六进制码存放在数据库中,如果图片尺寸很大,尤其像商品详情那样的长图来说,不管是存储还是网络传输,都是非常消耗性能的,所以富文本中的图片也需要上传至服务器。我的后台管理系统使用的是的react框架,用到的一款富文本编辑组件是wangeditor,该组件可以设置嵌套图片的上传路径以及大小限制,非常方便,推荐使用。

下列是我的后台管理系统自己封装的富文本组件:

import React from 'react';
import PropTypes from 'prop-types';
import { noop, get } from 'lodash';
import E from 'wangeditor';
import { message } from 'antd';
import CustomConfig from '../../../../env'
import {getToken} from "../../../../utils/authority"; export class RichTextEditor extends React.Component {
componentDidMount() {
const { value, onChange } = this.props;
const elem = this.editor;
const editor = new E(elem);
this.configUploadPic(editor);
// 使用 onchange 函数监听内容的变化,并实时更新到 state 中
editor.customConfig.onchange = html => {
onChange(html);
};
editor.create();
editor.txt.html(value);
} configUploadPic = editor => {
editor.customConfig.uploadImgServer = CustomConfig.BASE_URL + '/api/file/upload_embed_image';
editor.customConfig.uploadImgHeaders = {
//添加token
authorization: getToken(),
};
editor.customConfig.uploadImgMaxSize = 5 * 1024 * 1024; // 图片大小限制5M
editor.customConfig.uploadImgMaxLength = 1; //一次最多一张图片
editor.customConfig.uploadImgTimeout = 25000; //25秒超时
editor.customConfig.uploadFileName = 'file';
editor.customConfig.customAlert = function(info) {
// info 是需要提示的内容
console.log(info);
};
editor.customConfig.uploadImgHooks = {
error: function(xhr, editor) {
// 图片上传出错时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
message.error(`图片上传失败,${get(xhr, ['responseText'])}`);
},
timeout: function(xhr, editor) {
// 图片上传超时时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
message.error(`图片上传超时!`);
}, // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
// (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
customInsert: function(insertImg, result, editor) {
// 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
// insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果 // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
const url = result.url;
insertImg(url);
// result 必须是一个 JSON 格式字符串!!!否则报错
},
};
}; render() {
return (
<div
ref={ref => {
this.editor = ref;
}}
/>
);
}
} RichTextEditor.protoType = {
value: PropTypes.string,
onChange: PropTypes.func,
}; RichTextEditor.defaultProps = {
value: '',
onChange: noop,
};

顺便提一下,lodash是一款非常方便、高效的集合处理工具,推荐使用。

回到正题

由于我使用的是阿里提供的OSS对象存储,我在网上查找了相关的资料,都找不到相应的解决方案,最后查看了官方的开发文档,设置Content-type之后终于得到解决,下面是相关代码(使用kotlin):

    private fun MultipartFile.savePic(folderName:String = "pic"):String {
fun getExtension(): String {
val extension = this.originalFilename.orEmpty().substringAfterLast(".", "")
return if (extension.isEmpty()) {
""
} else
".$extension"
} // 添加 ContentType (添加后可在浏览器中直接浏览,而非下载链接)
val objectMetadata = ObjectMetadata()
objectMetadata.contentType = "image/jpg" val objName = "$folderName/${UUID.randomUUID()}${getExtension()}"
try {
ossClient.putObject(bucketName, objName, this.inputStream, objectMetadata)
} catch (e: Exception) {
logger.error("上传图片失败", e)
throw BadRequestException("上传图片失败")
}
return objName
}

最新文章

  1. 【原创】Kafka topic常见命令解析
  2. nodejs研究笔记
  3. Centos 6.X基本维护操作
  4. height:100%和height:auto的区别
  5. iOS相关,过年回来电脑上的证书都失效了,解决方法。
  6. printf用法之打印2进制,八进制,十进制,十六进制
  7. Android事件详解——拖放事件DragEvent
  8. Caffe代码分析--crop_layer.cu
  9. 201521123101 《Java程序设计》第11周学习总结
  10. Project Euler:Product-sum numbers (problem 88) C++
  11. [物理学与PDEs]第1章第1节 引言
  12. 利用C#进行AUTOCAD的二次开发
  13. JVM GC-----2、垃圾标记算法(一)
  14. uvalive 4452 The Ministers’ Major Mess
  15. su - oracle /bin/bash: Permission denied
  16. 【python学习-2】python起步必备
  17. 2017ACM暑期多校联合训练 - Team 9 1010 HDU 6170 Two strings (dp)
  18. (五)静态断言(下),static_assert
  19. 创业公司感悟录之十个提醒—by李天平
  20. bzoj 3714 [PA2014]Kuglarz 最小生成树

热门文章

  1. VMware station 安装报错 failed to install the hcmon driver
  2. Pytorch: 命名实体识别: BertForTokenClassification/pytorch-crf
  3. 深入java面向对象二:final关键字
  4. js 制作分页
  5. python基础八之文件操作
  6. UVa 1354 Mobile Computing[暴力枚举]
  7. P1057 迷宫路径
  8. vue项目上滑滚动加载更多&amp;下拉刷新
  9. ZR并查集专题
  10. 2018-9-30-C#-传入-params-object-长度