最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue + WebApi 實現(xiàn)上傳下載功能(完整示例)

 更新時間:2025年10月22日 15:41:41   作者:_tiddler  
本文通過實例代碼介紹Vue + WebApi實現(xiàn)上傳下載功能,本文通過實例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

vue上傳:

UI:

  <el-button
        size="mini"
        type="text"
        icon="el-icon-document-add"
        @click="handleUpload()"
        >上傳
      </el-button>
      <el-dialog
        :title="Title"
        :visible.sync="open"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-upload
          ref="upload"
          :limit="1"
          :on-remove="handleRemove"
          :on-error="onError"
          :file-list="fileList"
          :auto-upload="false"
          :http-request="customUpload"
          action="http://localhost:5000/api/Resource/AddResource"
          class="upload-demo"
        >
          <el-button slot="trigger" size="small" type="primary"
            >選取文件</el-button
          >
          <el-button
            style="margin-left: 10px;"
            size="small"
            type="success"
            @click="submitUpload"
            >上傳到服務(wù)器</el-button
          >
          <div slot="tip" class="el-upload__tip">
            支持上傳 {{ strRebuild(fileType) }} 格式,且不超過 {{ fileSize }}M
          </div>
        </el-upload>
      </el-dialog>

點擊按鈕觸發(fā)方法,open為true 上傳彈窗出現(xiàn):

handleUpload() {
      this.title = "XXXX";
      this.open = true;
    },

選擇文件后,點擊上傳到服務(wù)器,觸發(fā)以下方法:

 customUpload(file) {
      console.debug("進(jìn)入上傳方法");
      const param = new FormData();
      param.append("files", file.file);
      console.log("上傳文件:", file);
      console.log("FormData:", param);
      uploadFile(param);
      setTimeout(() => {
        this.open = false;
        message("success", "上傳成功");
        this.$refs.upload.clearFiles();
        this.fileList = [];
      }, 1500);
    },

其中觸發(fā)封裝的請求方法:

export async function uploadFile(file) {
  try {
    console.log("上傳資源參數(shù):", file);
    // 嘗試不同的路徑格式
    
    const response = await request.post("/Resource/UploadFile", file);

    console.log("API響應(yīng):", response);
    return response;
  } catch (error) {
    console.error("獲取文章列表失敗:", error);
    throw error;
  }
}

.Net 后端Api:

/// <summary>
/// 上傳客戶端文件并保存
/// </summary>
[HttpPost("UploadFile")]
public async Task<IActionResult> UploadFile(IFormFileCollection files)
{
    foreach (var file in files)
    {
        // 判斷文件是否有內(nèi)容
        if (file.Length == 0)
        {
            Console.WriteLine("該文件無任何內(nèi)容!!!");
            continue;
        }
        // 獲取附件原名
        string fileName = file.FileName;
        // 如果是獲取的含有路徑的文件名,那么截取掉多余的,只剩下文件名和后綴名
        if (fileName.Contains("\\"))
        {
            int index = fileName.LastIndexOf("\\");
            fileName = fileName.Substring(index + 1);
        }
        // 判斷單個文件大于1M
        long fileSize = file.Length;
        if (fileSize > 1024 * 1024)
        {
            Console.WriteLine($"文件大小為(單位字節(jié)):{fileSize}");
            Console.WriteLine("該文件大于1M");
        }
        // 構(gòu)建完整保存路徑
        var fullPath = Path.Combine(_webHostEnvironment.WebRootPath, $"Resources/{Guid.NewGuid()}{fileName}");
        var directory = Path.Combine(_webHostEnvironment.WebRootPath, $"Resources");
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        try
        {
            // 將文件保存到指定位置
            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            return StatusCode(500, new { message = "文件上傳失敗", error = e.Message });
        }
    }
    return Ok(new { success = true, message = "上傳成功" });
}

可以使用IFormFileCollection 接口類型對接前端的FormData類型。通過FileStream 類傳輸文件。

因為_webHostEnvironment.WebRootPath對應(yīng)wwwroot,所以文件會保存在wwwroot目錄下。

其實應(yīng)該有對應(yīng)的表格。上傳的文件信息會保存在數(shù)據(jù)庫里,這里圖方便就沒寫。

下載:

下載的方法有很多種,這里展示Fetch下載:

 downloadFile(fileName) {
      const fileUrl = this.$baseURL + "\\Resources\\" + fileName; // 文件的URL地址
      fetch(fileUrl)
        .then((response) => response.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
        })
        .catch((error) => {
          console.error(error);
        });
    },

按鈕調(diào)用:

<button @click="downloadFile('test.png')">下載文件2</button>

在方法里直接拼接了圖片(其他文件類似)的url,會在瀏覽器中下載以下圖片:

完整vue代碼:

<template>
  <div class="front-container">
    <div>
      <h2>往昔崢嶸</h2>
      <el-button
        size="mini"
        type="text"
        icon="el-icon-document-add"
        @click="handleUpload()"
        >上傳
      </el-button>
      <el-dialog
        :title="Title"
        :visible.sync="open"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-upload
          ref="upload"
          :limit="1"
          :on-remove="handleRemove"
          :on-error="onError"
          :file-list="fileList"
          :auto-upload="false"
          :http-request="customUpload"
          action="http://localhost:5000/api/Resource/AddResource"
          class="upload-demo"
        >
          <el-button slot="trigger" size="small" type="primary"
            >選取文件</el-button
          >
          <el-button
            style="margin-left: 10px;"
            size="small"
            type="success"
            @click="submitUpload"
            >上傳到服務(wù)器</el-button
          >
          <div slot="tip" class="el-upload__tip">
            支持上傳 {{ strRebuild(fileType) }} 格式,且不超過 {{ fileSize }}M
          </div>
        </el-upload>
      </el-dialog>
      <button @click="downloadFile('test.png')">下載文件2</button>
    </div>
    <div class="blog-list">
      <BlogCard
        v-for="blog in blogs"
        :key="blog.id"
        :blog="blog"
        @view-detail="handleViewDetail"
      />
    </div>
  </div>
</template>
<script>
import { lastSubstring, strRebuildEx } from "@/utils/util";
import { message } from "@/utils/message";
import { blogList } from "../mock/blogData.ts";
import { uploadFile } from "@/api/resources";
import BlogCard from "@/components/BlogCard.vue";
export default {
  name: "BlogList",
  components: {
    BlogCard,
  },
  data() {
    return {
      Title: "上傳組件",
      open: false,
      blogs: blogList,
      // 附件列表
      fileList: [],
      // 允許的文件類型,可依據(jù)實際需求增加格式
      fileType: [
        "xls",
        "xlsx",
        "pdf",
        "doc",
        "docx",
        "txt",
        "jpg",
        "png",
        "jpeg",
        "zip",
      ],
      //fileType: ["pdf", "doc", "zip"],
      // 運行上傳文件大小,單位 M
      fileSize: 10,
    };
  },
  methods: {
    handleViewDetail(blog) {
      console.log("查看博客詳情:", blog);
    },
    // downloadFile(fileName) {
    //   const fileUrl = this.$baseURL + "\\Resources\\" + fileName; // 文件的URL地址
    //   console.debug(fileUrl);
    //   const link = document.createElement("a");
    //   link.href = fileUrl;
    //   link.setAttribute("download", fileName);
    //   link.click();
    // },
    downloadFile(fileName) {
      const fileUrl = this.$baseURL + "\\Resources\\" + fileName; // 文件的URL地址
      fetch(fileUrl)
        .then((response) => response.blob())
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
        })
        .catch((error) => {
          console.error(error);
        });
    },
    handleUpload() {
      this.title = "XXXX";
      this.open = true;
    },
    // 清空表單
    clear() {
      // 清空附件
      this.$refs.upload.clearFiles();
    },
    // 附件檢查
    // 檢查附件是否屬于可上傳類型
    // 檢查附件是否超過限制大小
    checkFile() {
      var flag = true;
      var tip = "";
      var files = this.$refs.upload.uploadFiles;
      files.forEach((item) => {
        // 文件過大
        if (item.size > this.fileSize * 1024 * 1024) {
          flag = false;
          tip = " 文件超過" + this.fileSize + "M";
        }
        // 文件類型不屬于可上傳的類型
        if (!this.fileType.includes(lastSubstring(item.name, "."))) {
          flag = false;
          tip = " 文件類型不可上傳";
          this.clientOpen = false;
        }
      });
      if (!flag) {
        message("error", tip);
      }
      return flag;
    },
    // 提交附件
    submitUpload() {
      if (this.checkFile()) {
        console.log("上傳附件...");
        this.$refs.upload.submit();
      } else {
        console.log("取消上傳");
      }
    },
    // 自定義文件上傳方法
    customUpload(file) {
      console.debug("進(jìn)入上傳方法");
      const param = new FormData();
      param.append("files", file.file);
      // 模擬上傳成功
      console.log("上傳文件:", file);
      console.log("FormData:", param);
      uploadFile(param);
      // 模擬API調(diào)用
      setTimeout(() => {
        this.open = false;
        message("success", "上傳成功");
        this.$refs.upload.clearFiles();
        this.fileList = [];
      }, 1500);
    },
    // 移除附件
    handleRemove(file, fileList) {
      console.log("移除附件...");
    },
    // 附件上傳失敗,打印下失敗原因
    onError(err) {
      message("error", "附件上傳失敗");
      console.log(err);
    },
    strRebuild(arr) {
      strRebuildEx(arr, ",");
    },
  },
};
</script>
<style>
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #2c3e50;
  padding: 1rem 2rem;
}
.nav-brand {
  color: white;
  font-size: 1.2rem;
  font-weight: bold;
}
.nav-links {
  display: flex;
  align-items: center;
  gap: 0;
}
.nav-link {
  color: white;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  transition: all 0.3s ease;
  white-space: nowrap;
}
.nav-link:hover {
  background-color: #34495e;
  transform: translateY(-1px);
}
.router-link-active {
  background-color: #42b883;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.separator {
  width: 1px;
  height: 20px;
  background-color: rgba(255, 255, 255, 0.3);
  margin: 0 0.5rem;
}
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.viewmore-row {
  float: right;
  background: #12b7de;
  color: #fff;
  border-radius: 3px;
  padding: 0px 10px;
  height: 30px;
}
.bg-purple {
  background: #eaeaea;
  -webkit-animation: loading 1s ease-in-out infinite;
  animation: loading 1s ease-in-out infinite;
}
@keyframes loading {
  0% {
    width: 90%;
  }
  50% {
    width: 100%;
  }
  to {
    width: 90%;
  }
}
[v-cloak] {
  display: none !important;
}
</style>

根據(jù)自己需要把其中報錯,不相干的代碼刪減掉。

到此這篇關(guān)于Vue + WebApi 實現(xiàn)上傳下載功能的文章就介紹到這了,更多相關(guān)Vue WebApi上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Vue計算屬性computed與方法methods的區(qū)別及說明

    Vue計算屬性computed與方法methods的區(qū)別及說明

    這篇文章主要介紹了Vue計算屬性computed與方法methods的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • vue-cli打包后本地運行dist文件中的index.html操作

    vue-cli打包后本地運行dist文件中的index.html操作

    這篇文章主要介紹了vue-cli打包后本地運行dist文件中的index.html操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • 可控制緩存銷毀的?keepAlive?組件實現(xiàn)詳解

    可控制緩存銷毀的?keepAlive?組件實現(xiàn)詳解

    這篇文章主要為大家介紹了可控制緩存銷毀的?keepAlive?組件實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • 淺談VUE uni-app 自定義組件

    淺談VUE uni-app 自定義組件

    這篇文章主要介紹了uni-app 的自定義組件,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-10-10
  • vue源碼之批量異步更新策略的深入解析

    vue源碼之批量異步更新策略的深入解析

    這篇文章主要給大家介紹了關(guān)于vue源碼之批量異步更新策略的相關(guān)資料,關(guān)于vue異步更新是我們?nèi)粘i_發(fā)中經(jīng)常遇到的一個功能,需要的朋友可以參考下
    2021-05-05
  • 前端vue-cli項目中使用img圖片和background背景圖的幾種方法

    前端vue-cli項目中使用img圖片和background背景圖的幾種方法

    這篇文章主要介紹了前端vue-cli項目中使用img圖片和background背景圖的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Vue.js實現(xiàn)數(shù)據(jù)響應(yīng)的方法

    Vue.js實現(xiàn)數(shù)據(jù)響應(yīng)的方法

    這篇文章主要介紹了Vue.js實現(xiàn)數(shù)據(jù)響應(yīng)的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-08-08
  • vue3使用video.js播放m3u8格式視頻的操作指南

    vue3使用video.js播放m3u8格式視頻的操作指南

    有時候我們需要播放 m3u8 格式的視頻,或者實現(xiàn)視頻播放器更多定制化需求,HTML 的 video 元素?zé)o法實現(xiàn)這些需求,這時候可以考慮使用 Video.js,本文給大家介紹了vue3使用video.js播放m3u8格式視頻的操作指南,需要的朋友可以參考下
    2024-07-07
  • 解決el-dialog與el-tabs一起用卡死的問題

    解決el-dialog與el-tabs一起用卡死的問題

    在el-dialog中嵌入el-tabs和el-transfer時,關(guān)閉dialog會導(dǎo)致瀏覽器卡死,通過排查發(fā)現(xiàn)是destroy-on-close屬性和el-tabs沖突導(dǎo)致的,解決方法是去掉destroy-on-close屬性或給el-tabs添加v-if
    2026-01-01
  • vue修改this.$confirm的文字樣式、自定義樣式代碼實例

    vue修改this.$confirm的文字樣式、自定義樣式代碼實例

    this.$confirm是一個?Vue.js?中的彈窗組件,其樣式可以通過?CSS?進(jìn)行自定義,下面這篇文章主要給大家介紹了關(guān)于vue修改this.$confirm的文字樣式、自定義樣式的相關(guān)資料,需要的朋友可以參考下
    2024-02-02

最新評論

乌拉特中旗| 古丈县| 闸北区| 保亭| 阿坝| 中阳县| 溧水县| 锡林浩特市| 台前县| 九台市| 香港| 沅江市| 山东| 开阳县| 新余市| 南皮县| 宜宾市| 永城市| 新营市| 登封市| 静安区| 马山县| 青州市| 名山县| 禹州市| 聂荣县| 汉寿县| 平武县| 安化县| 达孜县| 元朗区| 奎屯市| 扎兰屯市| 陆河县| 巨鹿县| 颍上县| 汤阴县| 廉江市| 红河县| 思南县| 营山县|