文件上传及下载(img、文档、压缩包)

<a href="路径" download>下载</a>

bug

不支持微信公众号
下载图片一致提示跨域,换成https 好了
在这里插入图片描述

common.js

//请求的域名
// export let baseURL = "http://test.tieqiao.shop";
import { Toast, Dialog } from "vant"; //引入vant提示框

/*将base64转换为file*/
export function dataURLtoFile(dataurl, filename) {
  //将base64转换为文件
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime
  });
}

// ajax上传图片——文件流方式
export function upload(base64, name) {
  return new Promise((resolve, reject) => {
    Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true, // 禁用背景点击
      mask: false // 是否显示遮罩层
      // message: "图片上传中..."
    });
    lrz(base64, {
      quality: 0.5
    }).then(function(rst) {
      // 处理成功会执行
      // console.log("压缩:", rst);
      let file = dataURLtoFile(rst.origin, name);
      // 实例化FormData;
      var formdata = new FormData();
      //  将文件信息存入formdata,键名为file
      //  formdata会将文件信息序列化为ajax可识别的数据类型
      formdata.append("file", file);

      $.ajax({
        type: "post",
        url: `${localStorage.getItem(
          "baseURL"
        )}/api/common/uploadali?token=${localStorage.getItem(
          "token" + localStorage.getItem("sign_id")
        )}&sign_id=${localStorage.getItem("sign_id")}`,
        data: formdata, // formdata直接赋值给data
        processData: false, //formdata已将数据序列化,无需在处理
        contentType: false, //formdata无需设置请求头
        success: function(res) {
          Toast.clear();
          resolve(res.data);
        }
      });
    });
  });
}

// ajax上传素材文件
export function upfile(e) {
  return new Promise((resolve, reject) => {
    Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true, // 禁用背景点击
      mask: false // 是否显示遮罩层
      // message: "图片上传中..."
    });
    // 处理成功会执行
    // 获取文件信息
    var file = e.target.files[0];
    // 实例化FormData;
    var formdata = new FormData();
    //  将文件信息存入formdata,键名为file
    //  formdata会将文件信息序列化为ajax可识别的数据类型
    formdata.append("file", file);
    $.ajax({
      type: "post",
      url: `${localStorage.getItem(
        "baseURL"
      )}/api/common/uploadali?token=${localStorage.getItem(
        "token" + localStorage.getItem("sign_id")
      )}&sign_id=${localStorage.getItem("sign_id")}`,
      data: formdata, // formdata直接赋值给data
      processData: false, //formdata已将数据序列化,无需在处理
      contentType: false, //formdata无需设置请求头
      success: function(res) {
        console.log(9999999999, res);

        Toast.clear();
        resolve(res.data);
      }
    });
  });
}

// 下载文件(图片、文档、压缩包)到手机相册
// 将文件地址转为blob二进制对象
function getFile(src) {
  return new Promise(resolve => {
    let xhr = new XMLHttpRequest();
    xhr.responseType = "blob";
    xhr.onprogress = function(e) {
      console.log(
        "当前数据获取进度为" + ((e.loaded * 100) / e.total).toFixed(2) + "%"
      );
    };
    xhr.onreadystatechange = function() {
      if (this.readyState === 4) {
        resolve(this.response);
      }
    };
    xhr.open("get", src);
    xhr.send();
  });
}
// 下载文件到本地
import { saveAs } from "./FileSaver";
export function downFile(src) {
  getFile(src).then(res => {
    console.log(1111111111, res);
    saveAs(res, new Date().getTime() + "" + Math.round(Math.random() * 10000));
  });
}

/**
 * mescroll封装
 */
import MeScroll from "mescroll.js";
export function initMeScroll(mescrollId, options) {
  let myOption = {
    // down:{}, //下拉刷新的配置. (如果下拉刷新和上拉加载处理的逻辑是一样的,则down可不用写了)
    up: {
      page: {
        num: 0, // 当前页 默认0,回调之前会加1; 即callback(page)会从1开始
        size: 10, // 每页数据条数
        time: null // 加载第一页数据服务器返回的时间; 防止用户翻页时,后台新增了数据从而导致下一页数据重复;
      },
      loadFull: {
        use: false, // 列表数据过少,不足以滑动触发上拉加载,是否自动加载下一页,直到满屏或者无更多数据为止;默认false,因为可通过调高page.size或者嵌套mescroll-bounce的div避免这个情况
        delay: 500 // 延时执行的毫秒数; 延时是为了保证列表数据或占位的图片都已初始化完成,且下拉刷新上拉加载中区域动画已执行完毕;
      },
      // toTop: {
      //     //回到顶部按钮
      //     src: "./static/mescroll/mescroll-totop.png", //图片路径,默认null,支持网络图
      //     offset: 1000, //列表滚动1000px才显示回到顶部按钮
      // },
      noMoreSize: 10, // 如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
      // htmlNodata: '<p class="upwarp-nodata">-- 暂无更多数据 --</p>', // 无数据的布局
      htmlLoading:
        '<p class="upwarp-progress mescroll-rotate"></p ><p class="upwarp-tip">正在加载...</p >', // 上拉加载中的布局
      lazyLoad: {
        use: true, // 是否开启懒加载,默认false
        attr: "imgurl", // html标签中,存放网络图片地址的属性名: <img src='占位图' imgurl='网络图'/>
        showClass: "mescroll-lazy-in", // 显示样式,参见mescroll.css
        delay: 500, // 列表滚动的过程中每500ms检查一次图片是否在可视区域,如果在可视区域则加载图片
        offset: 200 // 超出可视区域200px的图片仍可触发懒加载,目的是提前加载部分图片
      }
      // toTop: {
      //     //回到顶部按钮
      //     src: require(""), //图片路径,默认null,支持网络图
      //     offset: 600 //列表滚动1000px才显示回到顶部按钮
      // },
    }
  };
  //加入自定义的默认配置
  options = MeScroll.extend(options, myOption);
  //创建MeScroll对象
  return new MeScroll(mescrollId, options);
}

FileSaver.js (下载)

/*! FileSaver.js
 *  A saveAs() FileSaver implementation.
 *  2014-01-24
 *
 *  By Eli Grey, http://eligrey.com
 *  License: X11/MIT
 *    See LICENSE.md
 */

/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */

export var saveAs =
  saveAs ||
  // IE 10+ (native saveAs)
  (typeof navigator !== "undefined" &&
    navigator.msSaveOrOpenBlob &&
    navigator.msSaveOrOpenBlob.bind(navigator)) ||
  // Everyone else
  (function(view) {
    "use strict";
    // IE <10 is explicitly unsupported
    if (
      typeof navigator !== "undefined" &&
      /MSIE [1-9]\./.test(navigator.userAgent)
    ) {
      return;
    }
    var doc = view.document,
      // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
      get_URL = function() {
        return view.URL || view.webkitURL || view;
      },
      URL = view.URL || view.webkitURL || view,
      save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
      can_use_save_link = !view.externalHost && "download" in save_link,
      click = function(node) {
        var event = doc.createEvent("MouseEvents");
        event.initMouseEvent(
          "click",
          true,
          false,
          view,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
        node.dispatchEvent(event);
      },
      webkit_req_fs = view.webkitRequestFileSystem,
      req_fs =
        view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem,
      throw_outside = function(ex) {
        (view.setImmediate || view.setTimeout)(function() {
          throw ex;
        }, 0);
      },
      force_saveable_type = "application/octet-stream",
      fs_min_size = 0,
      deletion_queue = [],
      process_deletion_queue = function() {
        var i = deletion_queue.length;
        while (i--) {
          var file = deletion_queue[i];
          if (typeof file === "string") {
            // file is an object URL
            URL.revokeObjectURL(file);
          } else {
            // file is a File
            file.remove();
          }
        }
        deletion_queue.length = 0; // clear queue
      },
      dispatch = function(filesaver, event_types, event) {
        event_types = [].concat(event_types);
        var i = event_types.length;
        while (i--) {
          var listener = filesaver["on" + event_types[i]];
          if (typeof listener === "function") {
            try {
              listener.call(filesaver, event || filesaver);
            } catch (ex) {
              throw_outside(ex);
            }
          }
        }
      },
      FileSaver = function(blob, name) {
        // First try a.download, then web filesystem, then object URLs
        var filesaver = this,
          type = blob.type,
          blob_changed = false,
          object_url,
          target_view,
          get_object_url = function() {
            var object_url = get_URL().createObjectURL(blob);
            deletion_queue.push(object_url);
            return object_url;
          },
          dispatch_all = function() {
            dispatch(
              filesaver,
              "writestart progress write writeend".split(" ")
            );
          },
          // on any filesys errors revert to saving with object URLs
          fs_error = function() {
            // don't create more object URLs than needed
            if (blob_changed || !object_url) {
              object_url = get_object_url(blob);
            }
            if (target_view) {
              target_view.location.href = object_url;
            } else {
              window.open(object_url, "_blank");
            }
            filesaver.readyState = filesaver.DONE;
            dispatch_all();
          },
          abortable = function(func) {
            return function() {
              if (filesaver.readyState !== filesaver.DONE) {
                return func.apply(this, arguments);
              }
            };
          },
          create_if_not_found = { create: true, exclusive: false },
          slice;
        filesaver.readyState = filesaver.INIT;
        if (!name) {
          name = "download";
        }
        if (can_use_save_link) {
          object_url = get_object_url(blob);
          // FF for Android has a nasty garbage collection mechanism
          // that turns all objects that are not pure javascript into 'deadObject'
          // this means `doc` and `save_link` are unusable and need to be recreated
          // `view` is usable though:
          doc = view.document;
          save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a");
          save_link.href = object_url;
          save_link.download = name;
          var event = doc.createEvent("MouseEvents");
          event.initMouseEvent(
            "click",
            true,
            false,
            view,
            0,
            0,
            0,
            0,
            0,
            false,
            false,
            false,
            false,
            0,
            null
          );
          save_link.dispatchEvent(event);
          filesaver.readyState = filesaver.DONE;
          dispatch_all();
          return;
        }
        // Object and web filesystem URLs have a problem saving in Google Chrome when
        // viewed in a tab, so I force save with application/octet-stream
        // http://code.google.com/p/chromium/issues/detail?id=91158
        if (view.chrome && type && type !== force_saveable_type) {
          slice = blob.slice || blob.webkitSlice;
          blob = slice.call(blob, 0, blob.size, force_saveable_type);
          blob_changed = true;
        }
        // Since I can't be sure that the guessed media type will trigger a download
        // in WebKit, I append .download to the filename.
        // https://bugs.webkit.org/show_bug.cgi?id=65440
        if (webkit_req_fs && name !== "download") {
          name += ".download";
        }
        if (type === force_saveable_type || webkit_req_fs) {
          target_view = view;
        }
        if (!req_fs) {
          fs_error();
          return;
        }
        fs_min_size += blob.size;
        req_fs(
          view.TEMPORARY,
          fs_min_size,
          abortable(function(fs) {
            fs.root.getDirectory(
              "saved",
              create_if_not_found,
              abortable(function(dir) {
                var save = function() {
                  dir.getFile(
                    name,
                    create_if_not_found,
                    abortable(function(file) {
                      file.createWriter(
                        abortable(function(writer) {
                          writer.onwriteend = function(event) {
                            target_view.location.href = file.toURL();
                            deletion_queue.push(file);
                            filesaver.readyState = filesaver.DONE;
                            dispatch(filesaver, "writeend", event);
                          };
                          writer.onerror = function() {
                            var error = writer.error;
                            if (error.code !== error.ABORT_ERR) {
                              fs_error();
                            }
                          };
                          "writestart progress write abort"
                            .split(" ")
                            .forEach(function(event) {
                              writer["on" + event] = filesaver["on" + event];
                            });
                          writer.write(blob);
                          filesaver.abort = function() {
                            writer.abort();
                            filesaver.readyState = filesaver.DONE;
                          };
                          filesaver.readyState = filesaver.WRITING;
                        }),
                        fs_error
                      );
                    }),
                    fs_error
                  );
                };
                dir.getFile(
                  name,
                  { create: false },
                  abortable(function(file) {
                    // delete file if it already exists
                    file.remove();
                    save();
                  }),
                  abortable(function(ex) {
                    if (ex.code === ex.NOT_FOUND_ERR) {
                      save();
                    } else {
                      fs_error();
                    }
                  })
                );
              }),
              fs_error
            );
          }),
          fs_error
        );
      },
      FS_proto = FileSaver.prototype,
      saveAs = function(blob, name) {
        return new FileSaver(blob, name);
      };
    FS_proto.abort = function() {
      var filesaver = this;
      filesaver.readyState = filesaver.DONE;
      dispatch(filesaver, "abort");
    };
    FS_proto.readyState = FS_proto.INIT = 0;
    FS_proto.WRITING = 1;
    FS_proto.DONE = 2;

    FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;

    view.addEventListener("unload", process_deletion_queue, false);
    saveAs.unload = function() {
      process_deletion_queue();
      view.removeEventListener("unload", process_deletion_queue, false);
    };
    return saveAs;
  })(
    (typeof self !== "undefined" && self) ||
      (typeof window !== "undefined" && window) ||
      this.content
  );
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window

input上传文件

在这里插入图片描述

		<div>上传附件</div>
        <input  type="file" @change="getFile($event)" />
import { upfile } from "../../../common/js/common";
 // 上传附件
    getFile(e) {
      console.log(e.target.files[0]);
      upfile(e).then(data => {
        this.fujian = data.url;
      });
    }

下载文件到本地

在这里插入图片描述

		  <span title="item.enclosure">附件</span>
          <van-button
            type="primary"
            color="linear-gradient(to right, #4bb0ff, #6149f6)"
            size="mini"
            @click="download(item.enclosure)"
          >下载</van-button>
 import { downFile } from "../../../common/js/common";
 // 点击下载附件
    download(src) {
      downFile(src);
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小曲曲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值