js下载文档对应的application类型

/**
 * [getFileType 下载文档对应的类型]
 * @param  {[type]} type [description]
 * @param  {[type]} id   [description]
 * @return {[type]}      [description]
 */
export function getFileType(id) {
  let arr = [
    { type: "doc", application: "application/msword" },
    {
      type: "docx",
      application:
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    },
    { type: "dot", application: "application/msword" },
    {
      type: "dotx",
      application:
        "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
    },
    { type: "xls", application: "application/vnd.ms-excel" },
    {
      type: "xlsx",
      application:
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    },
    { type: "ppt", application: "application/vnd.ms-powerpoint" },
    {
      type: "pptx",
      application:
        "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    },
    { type: "pdf", application: "application/pdf" },
    { type: "txt", application: "text/plain" },
    { type: "gif", application: "image/gif" },
    { type: "jpeg", application: "image/jpeg" },
    { type: "jpg", application: "image/jpeg" },
    { type: "png", application: "image/png" },
    { type: "css", application: "text/css" },
    { type: "html", application: "text/html" },
    { type: "htm", application: "text/html" },
    { type: "xsl", application: "text/xml" },
    { type: "xml", application: "text/xml" },
    { type: "mpeg", application: "video/mpeg" },
    { type: "mpg", application: "video/mpeg" },
    { type: "avi", application: "video/x-msvideo" },
    { type: "movie", application: "video/x-sgi-movie" },
    { type: "bin", application: "application/octet-stream" },
    { type: "exe", application: "application/octet-stream" },
    { type: "so", application: "application/octet-stream" },
    { type: "dll", application: "application/octet-stream" },
    { type: "ai", application: "application/postscript" },
    { type: "dir", application: "application/x-director" },
    { type: "js", application: "application/x-javascript" },
    { type: "swf", application: "application/x-shockwave-flash" },
    { type: "xhtml", application: "application/xhtml+xml" },
    { type: "xht", application: "application/xhtml+xml" },
    { type: "zip", application: "application/zip" },
    { type: "mid", application: "audio/midi" },
    { type: "midi", application: "audio/midi" },
    { type: "mp3", application: "audio/mpeg" },
    { type: "rm", application: "audio/x-pn-realaudio" },
    { type: "rpm", application: "audio/x-pn-realaudio-plugin" },
    { type: "wav", application: "audio/x-wav" },
    { type: "bmp", application: "image/bmp" }
  ];
  return findArrayReturnValue(arr, "type", id, "application");
}

通过文件流下载各种类型的代码

/** download All*/
const downMethod = data => {
  axios({
    method: data.method,
    url: apiUrl + data.url,
    params: data.params,
    responseType: "blob"
  }).then(res => {
    let timestamp = new Date().getTime();
    const link = document.createElement("a");
    let blob = new Blob([res.data], {
      type: getFileType(data.params.fileType)
    });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.download = data.fileName + moment(timestamp).format("YYYY-MM-DD"); //下载的文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
};

-

/**
 * @param arr 查找数组
 * @param property 查找属性
 * @param value 查找值
 * @des:查找到值后返回其值
 */
export const findArrayReturnValue = (arr, property, value, findKey) => {
  let len, findValue;
  if (!Array.isArray(arr)) {
    return;
  }
  len = arr.length;
  for (var i = 0; i < len; i++) {
    if (
      arr[i].hasOwnProperty(property) &&
      arr[i][property] == value &&
      arr[i].hasOwnProperty(findKey)
    ) {
      findValue = arr[i][findKey];
      break;
    }
  }
  return findValue;
};

版权声明:本文为博主原创文章,把本人CSDN文章搬来知乎分享给更多开发者。

CSDN本文链接:blog.csdn.net/weixin_38

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现这个功能,需要完成以下几个步骤: 1. 在视图中添加一个左侧的输入框和一个右侧的下载按钮,并设置它们的 ID 属性,方便在后续的代码中获取它们的值。 ```html <div> <input type="text" id="docId" /> <button type="button" id="downloadBtn">下载</button> </div> ``` 2. 在 JavaScript 中,获取输入框和下载按钮的引用,并为下载按钮添加一个点击事件的监听器。在点击事件处理程序中,使用 Ajax 技术向服务器发送一个请求,请求服务器下载指定 ID 对应文档。在请求返回的回调函数中,提示用户下载文件。 ```javascript $(function () { $("#downloadBtn").click(function () { var docId = $("#docId").val(); // 获取输入框中的值 $.ajax({ url: "/Download/DownloadFile", // 请求的服务器端地址 type: "POST", // 请求方式 data: { "id": docId }, // 发送给服务器的数据 success: function (data) { // 请求成功的回调函数 if (data.success) { alert("文件下载成功!"); } else { alert("文件下载失败:" + data.message); } }, error: function () { // 请求失败的回调函数 alert("请求失败,请稍后重试!"); } }); }); }); ``` 3. 在服务器端,实现一个名为 "DownloadFile" 的控制器方法,用于响应下载请求。该方法接收一个文档的 ID 参数,并通过数据库存储过程获取该文档的文件路径,然后将该文件作为响应的内容返回给客户端。 ```csharp public ActionResult DownloadFile(string id) { // 调用数据库存储过程获取文件路径 string filePath = GetFilePathFromDatabase(id); if (string.IsNullOrEmpty(filePath)) { return Json(new { success = false, message = "文件不存在或已被删除!" }); } else { // 将文件作为响应的内容返回给客户端 return File(filePath, "application/octet-stream", Path.GetFileName(filePath)); } } // 调用数据库存储过程获取文件路径的方法 private string GetFilePathFromDatabase(string id) { string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand("YourStoredProcedureName", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@id", id); connection.Open(); string filePath = (string)command.ExecuteScalar(); connection.Close(); return filePath; } } } ``` 在上述代码中,需要注意以下几点: 1. 在服务器端,我们使用 ASP.NET MVC 框架提供的 "File" 方法来返回文件内容。该方法接收三个参数:文件路径、文件类型、文件名。其中,文件类型可以是任何合法的 MIME 类型,如果不确定文件类型,可以使用 "application/octet-stream",表示二进制流类型。 2. 在调用数据库存储过程获取文件路径时,需要根据自己的实际情况修改连接字符串和存储过程名。 3. 如果文件不存在或已被删除,需要向客户端返回一个错误信息,可以使用 JSON 格式返回。在客户端的 Ajax 回调函数中,根据返回的 JSON 数据来提示用户下载是否成功。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值