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

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
    }
posted @ 2019-12-18 10:33  健人雄  阅读(8122)  评论(0编辑  收藏  举报