Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

能在上传文件的时候,显示上传进度吗? #457

Closed
pengqian089 opened this issue Feb 20, 2024 · 1 comment
Closed

能在上传文件的时候,显示上传进度吗? #457

pengqian089 opened this issue Feb 20, 2024 · 1 comment

Comments

@pengqian089
Copy link

A great idea

我实现了一部分,在编辑器内显示上传进度,但是对于前端不太擅长,不知道能不能整合到 md-editor-v3?

/**
 * 上传
 * @param {FormData} formData FormData
 * @param {String} url 请求地址
 * @param {String} method 请求方法
 * @param {function(ProgressEvent<XMLHttpRequestEventTarget>)} upload 上传文件回调
 * @param {function(ProgressEvent<XMLHttpRequestEventTarget>)} download 下载结果回调
 * @param {function} callback 失败回调函数
 * */
export async function uploadAsync({formData, url, method = "POST", upload = null, download = null, callback = null}) {
    const xhr = new XMLHttpRequest();
    return await new Promise((resolve, reject) => {
        if (typeof (upload) === "function") {
            xhr.upload.addEventListener("progress", (event) => {
                if (event.lengthComputable) {
                    //console.log("upload progress:", event.loaded / event.total);
                    upload(event);
                }
            });
        }
        if (typeof (download) === "function") {
            xhr.addEventListener("progress", (event) => {
                if (event.lengthComputable) {
                    // console.log("download progress:", event.loaded / event.total);
                    download(event);
                }
            });
        }
        xhr.addEventListener("loadend", () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                //resolve(xhr.readyState === 4 && xhr.status === 200);
                let result = JSON.parse(xhr.responseText);
                if (result.success === 1) {
                    resolve(result.url);
                } else {
                    warning(result.message);
                    callbackFail(callback);
                    reject(result.msg);
                }
            } else {
                reject(xhr.responseText);
            }


        });
        xhr.open(method, `${host}${url}`, true);
        //xhr.setRequestHeader("Content-Type", "application/octet-stream");
        let token = getToken();
        if (!_.isEmpty(token)) {
            xhr.setRequestHeader("Authorization", `Bearer ${getToken()}`);
        }
        xhr.send(formData);
    });
}

目前上传、下载进度只有xhr的相关api才有,fetch还没有。

vue view:

      <md-editor
          :theme="getTheme()"
          ref="editorRef"
          v-model="mumble.markdown"
          :toolbars="toolbars"
          @onUploadImg="uploadImage"
          @onHtmlChanged="onHtmlChanged">
        <template #defToolbars>
          <normal-toolbar title="test">
            <template #trigger>
              <svg class="md-editor-icon" aria-hidden="true">
                <use xlink:href="#icon-mark"></use>
              </svg>
            </template>
          </normal-toolbar>
        </template>
      </md-editor>
import {uploadAsync} from 'xxx';

export default{
  methods: {
    async uploadImage(files, callback) {
      if (files.length <= 0) {
        this.warning("请选择图片");
        return;
      }
      let file = files[0];
      if (!file.type.startsWith("image")) {
        this.warning("请选择图片上传");
        return;
      }

      let formData = new FormData();
      formData.append("image", file);
      let that = this;
      let url = await uploadAsync({
        formData: formData,
        url: `${uploadAddress}`,
        upload: function (event) {
          console.log("upload progress:", event.loaded / event.total);
          let progress = event.loaded / event.total;
          let message = progress === 1 ? "上传完毕,正在处理..." : `上传进度:${event.loaded / event.total}`;
          that.$refs.editorRef?.insert(() => {
            return {
              targetValue: message,
              select: true,
              deviationStart: 0,
              deviationEnd: 0
            };
          });
        },
      });
      console.log(url);
      callback([url]);
    }
  }
}
@imzbf
Copy link
Owner

imzbf commented Feb 21, 2024

上传的动作现在是交给开发者处理的,这个进度你完全可以自己展示,比如一个小的弹窗,在内部展示这个暂时做不了

@imzbf imzbf closed this as completed Feb 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants