wangEditor Java富文本的图片上传

上一篇 wangEditor的配置:https://blog.csdn.net/qq_35349982/article/details/103288508

这里主要讲 java后台

我这里用的是七牛云

Controller层

package com.xianbaovip.project.Controller;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xianbaovip.project.Modle.dto.ImgResultDto;
import com.xianbaovip.project.Server.UploadImg.UploadImgService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadImgCrotroller {

    @Autowired
    private UploadImgService uploadImgService;
    
    @RequestMapping("/uploadImg")
    public String updata(@RequestParam(name="file") MultipartFile file) throws Exception {
    
    //首先判断是不是空的文件
        if (!file.isEmpty()) {
//            //对文文件的全名进行截取然后在后缀名进行删选。
//            int begin = file.getOriginalFilename().indexOf(".");
//            int last = file.getOriginalFilename().length();
//            String suffix = file.getOriginalFilename().substring(begin, last);
//
//            //读取文件的后缀名字
//            String fileName = imgId+suffix;
            //生成图片的唯一id
            String imgId = ObjectId.next();
            ImgResultDto imgResultDto = uploadImgService.uploadImage(imgId, file);
            String jsonStr= JSONUtil.toJsonStr(imgResultDto);
            return jsonStr;
        }else{
            JSONObject json1 = JSONUtil.createObj();
            json1.put("code", 300);
            json1.put("msg", "图片上传错误");
            String jsonStr= JSONUtil.toJsonStr(json1);
            return jsonStr;
        }
    }
}

Server层

package com.xianbaovip.project.Server.UploadImg;

import cn.hutool.core.util.StrUtil;
import com.xianbaovip.project.Common.constant;
import com.xianbaovip.project.Modle.dto.ImgResultDto;
import com.xianbaovip.project.Utils.UpdataImgUtils;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@PropertySource("classpath:common.properties")
public class UploadImgService {

    @Value("${imgServer}")
    private String imgServer;

    public ImgResultDto uploadImage(String imgId,MultipartFile file) throws IOException {

        String putRetKey = new UpdataImgUtils().UpdataImg(imgId, file.getBytes());
        String[] urlData = new String[1];

        ImgResultDto imgResultDto = new ImgResultDto();
        if(!StrUtil.hasBlank(putRetKey)){
            //设置返回值的类
            urlData[0] =imgServer+imgId;
            imgResultDto.setErrno(constant.imgErrorStart);//设置状态码
            imgResultDto.setData(urlData);
        }else{
            imgResultDto.setErrno(constant.imgErrorStart1);//设置状态码
        }

        return imgResultDto;
    }
}

工具类

package com.xianbaovip.project.Utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
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.context.annotation.PropertySource;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;


public  class UpdataImgUtils {


    private static final String img_Ak = "自行填写";
    private static final String img_Sk = "自行填写";
    private static final String img_Bucket = "自行填写";
    private static final String img_Url = "自行填写";


    public  String UpdataImg(String imgName, byte[] uploadBytes ){

        String putRetKey = "";
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传
        String accessKey = img_Ak;
        String secretKey = img_Sk;
        String bucket = img_Bucket;
        //如果是Windows情况下,格式是 E:\ss.jpg
        //String localFilePath = "E:\\ss.jpg";
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        //String key = null;
        //byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
        ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket,imgName);
        try {
            Response response = uploadManager.put(byteInputStream,imgName,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            putRetKey = putRet.key;

            System.out.println(putRet);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());

            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        return putRetKey;
    }
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了在Vue3中使用wangEditor富文本批量上传图片,你需要按照以下步骤进行操作: 1.首先,你需要安装wangEditor。你可以通过npm安装wangEditor,命令如下: ```shell npm install wangeditor --save ``` 2.在你的Vue组件中引入wangEditor,并在mounted钩子函数中初始化wangEditor。你需要在初始化时设置上传图片的配置,包括上传图片的路径和上传图片的处理函数。以下是一个示例: ```javascript <template> <div ref="editorElem" /> </template> <script> import wangEditor from 'wangeditor' export default { mounted() { const editor = new wangEditor(this.$refs.editorElem) // 配置上传图片的路径和处理函数 editor.customConfig.uploadImgServer = '/upload' editor.customConfig.uploadImgHooks = { before: function(xhr, editor, files) { // 在这里可以对上传的图片进行处理 }, success: function(xhr, editor, result) { // 图片上传成功后的处理函数 }, fail: function(xhr, editor, result) { // 图片上传失败后的处理函数 }, error: function(xhr, editor) { // 图片上传出错的处理函数 }, timeout: function(xhr, editor) { // 图片上传超时的处理函数 }, customInsert: function(insertImg, result, editor) { // 在这里可以对插入的图片进行处理 insertImg(result.data) } } editor.create() } } </script> ``` 在上面的代码中,你需要将`/upload`替换为你的图片上传路径。在`uploadImgHooks`中,你可以设置上传图片的处理函数,包括上传前的处理函数、上传成功后的处理函数、上传失败后的处理函数、上传出错的处理函数、上传超时的处理函数和插入图片后的处理函数。在`customInsert`函数中,你可以对插入的图片进行处理。 3.在你的服务器端设置图片上传的处理函数。在上传图片的处理函数中,你需要将上传的图片保存到服务器上,并返回一个JSON格式的数据,包括图片的URL和图片的宽度和高度。以下是一个示例: ```python import os from flask import Flask, request, jsonify from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) url = 'http://example.com/uploads/' + filename return jsonify({ 'errno': 0, 'data': [url], }) ``` 在上面的代码中,你需要将`http://example.com/uploads/`替换为你的图片上传路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值