国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

這篇具有很好參考價值的文章主要介紹了.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

首先本文參考的是,感謝博主:

net6WebApi上傳下載文件_cduoa的博客-CSDN博客_webapi下載文件

在博主的基礎(chǔ)上,增加了新的功能,代碼中有注明,并且使用VUE3前端實現(xiàn)。

后端部分:

1.首先建立IFileService文件

namespace net6ApiUploadAndDownload
{
    public interface IFileService
    {
        void UploadFile(List<IFormFile> files, string subDirectory);
        (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory);  //返回3個值
        string SizeConverter(long bytes);
    }

}

2.建立FileService文件

using System.IO.Compression;

namespace net6ApiUploadAndDownload;

public class FileService : IFileService
{
    #region Property

    private readonly IWebHostEnvironment webHostEnvironment;

    #endregion

    #region Constructor

    public FileService(IWebHostEnvironment webHostEnvironment)
    {
        this.webHostEnvironment = webHostEnvironment;
    }

    #endregion

    #region Upload File

    public void UploadFile(List<IFormFile> files, string subDirectory)
    {
        subDirectory = subDirectory ?? string.Empty;
        var target = Path.Combine(webHostEnvironment.ContentRootPath, subDirectory);

        Directory.CreateDirectory(target);

        //files.ForEach(async file =>
        //{
        //    if (file.Length <= 0) return;
        //    var filePath = Path.Combine(target, file.FileName);
        //    await using var stream = new FileStream(filePath, FileMode.Create);
        //    await file.CopyToAsync(stream);
        //});
        //此處使用async,超過30M的話,會報錯
        files.ForEach(file =>
        {
            if (file.Length <= 0) return;
            var filePath = Path.Combine(target, file.FileName);
            using var stream = new FileStream(filePath, FileMode.Create);
            file.CopyTo(stream);
        });
    }

    #endregion

    #region Download File

    public (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory)
    {
        var zipName = $"archive-{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.zip";

        //這里進行判斷,既能下載文件夾的內(nèi)容,又能下載單個文件
        List<string> files = new List<string>();
        if (subDirectory.Split('.').Length > 1) //上傳的是單個文件
        {
            files.Add(Path.Combine(webHostEnvironment.ContentRootPath, subDirectory));
        }
        else      //上傳的是文件夾的內(nèi)容
        {
            files = Directory.GetFiles(Path.Combine(webHostEnvironment.ContentRootPath, subDirectory)).ToList();
        }


        using var memoryStream = new MemoryStream();
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            files.ForEach(file =>
            {
                var theFile = archive.CreateEntry(Path.GetFileName(file));
                using var binaryWriter = new BinaryWriter(theFile.Open());
                binaryWriter.Write(File.ReadAllBytes(file));
            });
        }

        return ("application/zip", memoryStream.ToArray(), zipName);
    }

    #endregion

    #region Size Converter

    public string SizeConverter(long bytes)
    {
        var fileSize = new decimal(bytes);
        var kilobyte = new decimal(1024);
        var megabyte = new decimal(1024 * 1024);
        var gigabyte = new decimal(1024 * 1024 * 1024);

        return fileSize switch
        {
            _ when fileSize < kilobyte => "Less then 1KB",
            _ when fileSize < megabyte =>
                $"{Math.Round(fileSize / kilobyte, 0, MidpointRounding.AwayFromZero):##,###.##}KB",
            _ when fileSize < gigabyte =>
                $"{Math.Round(fileSize / megabyte, 2, MidpointRounding.AwayFromZero):##,###.##}MB",
            _ when fileSize >= gigabyte =>
                $"{Math.Round(fileSize / gigabyte, 2, MidpointRounding.AwayFromZero):##,###.##}GB",
            _ => "n/a"
        };
    }

    #endregion
}

3.增加FileController文件

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace net6ApiUploadAndDownload.Controllers
{
    [Route("api/[controller]/action")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly IFileService fileService;

        public FileController(IFileService fileService)
        {
            this.fileService = fileService;
        }
        /// <summary>
        ///  上傳功能
        /// </summary>
        /// <param name="formFiles">上傳的文件</param>
        /// <param name="subDirectory">把文件上傳到的具體的路徑</param>
        /// <returns></returns>
        [HttpPost(nameof(Upload))]
        //[RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = long.MaxValue)]
        [RequestSizeLimit(long.MaxValue)]        //默認是上傳30M,加上之后可,可以增大
        public IActionResult Upload([Required] List<IFormFile> formFiles, [Required] string subDirectory)
        {
            try
            {
                if (formFiles.Count > 0)
                {

                }
                fileService.UploadFile(formFiles, subDirectory);

                return Ok(new { formFiles.Count, Size = fileService.SizeConverter(formFiles.Sum(f => f.Length)) });
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        /// <summary>
        /// 下載功能
        /// </summary>
        /// <param name="subDirectory">下載文件夾的路徑或者下載的文件路徑</param>
        /// <returns></returns>
        [HttpGet(nameof(Download))]
        public IActionResult Download([Required] string subDirectory)
        {
            try
            {
                var (fileType, archiveData, archiveName) = fileService.DownloadFiles(subDirectory);

                return File(archiveData, fileType, archiveName);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}

4.Program文件中,進行配置和跨域的處理

using net6ApiUploadAndDownload;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddTransient<IFileService, FileService>();           //用AddTransient注入,每次都請求不同的實例
                                                                      //配置跨域服務(wù)
builder.Services.AddCors(options =>
{
    options.AddPolicy("cors", p =>
    {
        p.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();

    });
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors("cors");      //跨域
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

5.運行后的效果

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

6.Swagger就不用測試了,我們使用postman來測試一下上傳的接口

先輸入路徑

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

再選擇content-type?

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

最后選擇form-data,點擊發(fā)送按鈕,就會看到返回的路徑了

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

至此,后端完成。?

前端部分:

1.首先使用HBuilder X建立一個可運行的界面

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

2.然后寫入HelloWorld.vue代碼

<template>
	<el-upload ref="upload" action="#" multiple :file-list="fileList" :on-change="fileOnChange" :auto-upload="false">
		<el-button type="primary">上傳圖片</el-button>
	</el-upload>
	<el-button type="primary" @click="confirm">確定</el-button>
	<el-button type="success" @click="download">下載</el-button>
</template>

<script setup>
	import {
		reactive
	} from 'vue'
	import axios from 'axios'


	const fileList = reactive([])
	const formData = new FormData()

	const fileOnChange = (file) => {

		//下面部分可以對文件進行判斷
		const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type ===
			'image/gif');
		const isLt1M = file.size / 1024 / 1024 < 1;

		// if (!isIMAGE) {
		// 	alert('上傳文件只能是圖片格式!');
		// 	return false;
		// }
		// if (!isLt1M) {
		// 	alert('上傳文件大小不能超過 1MB!');
		// 	return false;
		// }
		var reader = new FileReader();
		reader.readAsDataURL(file.raw);
		reader.onload = function(e) {
			//console.log(e.currentTarget.result) //圖片的base64數(shù)據(jù)
			//str = str.replace(/^data:image\/\w+;base64,/, "")
		}


		if (file.status === 'ready') {
			console.log(1)
			fileList.push(file)
		}
	}

	//內(nèi)置地址
	let path = `C:\\Users\\Administrator\\Desktop\\圖片\\聲音`

	const download = () => {
		console.log(2)
		window.location.href = `https://localhost:7065/api/File/action/Download?subDirectory=${path}`
		// axios.get(`https://localhost:7065/api/File/action/Download?subDirectory=${path}`).then((res) => {
		// 	console.log(res)
		// 	if (res.status === 200) {
		// 		console.log(res.data.size)
		// 	}
		// })
	}
	const confirm = () => {
		console.log(formData.has('formFiles'))

		fileList.forEach((item, index) => {
			formData.append("formFiles", item.raw)
			//formData.append("subDirectory", 'file')
			console.log(item + index)
			console.log(2)
		})
		console.log(formData.has('formFiles'))
		uploadFiles(formData)
	}

	function uploadFiles(data) {
		axios.post("https://localhost:7065/api/File/action/Upload?subDirectory=1", data).then((res) => {
			console.log(res)
			if (res.status === 200) {
				console.log(res.data.size)
			}
		})
	}
</script>

3.點擊上傳功能

點擊上傳3張圖片,再點擊確定按鈕,可以看到下面有返回圖片的大小

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

此時api中也就有了圖片,1是文件夾的路徑

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

4.點擊下載功能

直接點擊下載按鈕,就會看到內(nèi)置路徑的文件,就會自動下載

.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程

5.源碼

net6ApiUploadAndDownload: net6ApiUploadAndDownload,VUE3上傳和下載功能

來源:.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-408671.html

到了這里,關(guān)于.net6Api后臺+VUE3前端實現(xiàn)上傳和下載文件全過程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)三:找回密碼界面及對應(yīng)功能實現(xiàn)

    基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)三:找回密碼界面及對應(yīng)功能實現(xiàn)

    ??本章實現(xiàn)找回密碼功能,包括短信驗證碼找回、郵箱驗證碼找回等功能,并通過node-send-email發(fā)送郵箱驗證碼,實現(xiàn)找回密碼界面、接口等功能。 1. 詳細課程地址: https://edu.csdn.net/course/detail/38183 2. 源碼下載地址: 點擊下載

    2024年02月12日
    瀏覽(23)
  • 基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)十六:統(tǒng)計報表模塊相關(guān)功能實現(xiàn)

    基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)十六:統(tǒng)計報表模塊相關(guān)功能實現(xiàn)

    ??本章使用Echarts及DataV實現(xiàn)常用圖表、特殊圖表、地圖及綜合圖表等圖表展示功能。 1. 詳細課程地址: https://edu.csdn.net/course/detail/38183 2. 源碼下載地址: 點擊下載 基于VUE3+Layui從

    2024年02月04日
    瀏覽(25)
  • 【.NET6 + Vue3 + CentOS7.9 + Docker + Docker-Compose + SSL】個人博客前后端運維部署

    【.NET6 + Vue3 + CentOS7.9 + Docker + Docker-Compose + SSL】個人博客前后端運維部署

    個人博客 前端:https://lujiesheng.cn 個人博客 后端:https://api.lujiesheng.cn 個人博客 運維:https://portainer.lujiesheng.cn 我采用的是 騰訊云輕量應(yīng)用服務(wù)器(2C 4G 8M 80G),配置如下圖: 安裝鏡像選擇 CentOS 7.6 64bit: 添加防火墻出入站規(guī)則,設(shè)置如下圖: 把已備案的域名解析到服務(wù)器

    2024年02月14日
    瀏覽(28)
  • 基于.NET6.0完全開源的MiniX后臺管理系統(tǒng),全端免費開源

    介紹 基于.NET 6.0打造的成熟后臺管理系統(tǒng)框架,完全開源免費免費,集成了LayUI,操作界面友好!已應(yīng)用到上百個項目,經(jīng)過多年的沉淀,開源給廣大用戶使用。 整套架構(gòu)包含后端\\\"miniAdmin\\\"+前端APP/小程序應(yīng)用“miniAPP”+PC端“miniPC”,全棧開源,永久免費。 符合國家安全三級

    2024年02月11日
    瀏覽(29)
  • Vite-Admin后臺管理系統(tǒng)|vite4+vue3+pinia前端后臺框架實例

    Vite-Admin后臺管理系統(tǒng)|vite4+vue3+pinia前端后臺框架實例

    基于 vite4.x+vue3+pinia 前端后臺管理系統(tǒng)解決方案 ViteAdmin 。 前段時間分享了一篇vue3自研pc端UI組件庫VEPlus。這次帶來最新開發(fā)的基于 vite4+vue3+pinia 技術(shù)棧搭配ve-plus組件庫構(gòu)建的中后臺權(quán)限管理系統(tǒng)框架。 支持vue-i18n國際化多語言、動態(tài)路由鑒權(quán)、4種布局模板及tab頁面緩存 等功

    2023年04月13日
    瀏覽(26)
  • 詳解 .Net6 Minimal API 的使用方式

    隨著 .Net6 的發(fā)布,微軟也改進了對之前 ASP.NET Core 構(gòu)建方式,使用了新的 Minimal API 模式。以前默認的方式是需要在 Startup 中注冊 IOC 和中間件相關(guān),但是在 Minimal API 模式下你只需要簡單的寫幾行代碼就可以構(gòu)建一個 ASP.NET Core的Web 應(yīng)用,可謂非常的簡單,加之配合 c# 的 glob

    2024年02月08日
    瀏覽(25)
  • 基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)八:自定義組件封裝上

    基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)八:自定義組件封裝上

    ??本章實現(xiàn)一些自定義組件的封裝,包括數(shù)據(jù)字典組件的封裝、下拉列表組件封裝、復(fù)選框單選框組件封裝、單選框組件封裝、文件上傳組件封裝、級聯(lián)選擇組件封裝、富文本組件封裝等。 1. 詳細課程地址: https://edu.csdn.net/course/detail/38183 2. 源碼下載地址: 點擊下載

    2024年02月12日
    瀏覽(26)
  • 基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)一:項目規(guī)劃及初始化

    基于VUE3+Layui從頭搭建通用后臺管理系統(tǒng)(前端篇)一:項目規(guī)劃及初始化

    ??使用vue3+Layui實現(xiàn)通用管理系統(tǒng)前端,使用vue3+layui搭建系統(tǒng)UI界面,使用nodejs搭建模擬web服務(wù)器,使用echarts實現(xiàn)系統(tǒng)可視化模塊,可以此項目為基礎(chǔ)進行擴展開發(fā),快速搭建管理系統(tǒng),具體內(nèi)容如下: ?? 1. 常見功能實現(xiàn): 實現(xiàn)用戶登錄(用戶名密碼登錄、手機驗證碼

    2024年02月13日
    瀏覽(29)
  • .Net6使用WebSocket與前端進行通信

    .Net6使用WebSocket與前端進行通信

    1. 創(chuàng)建類WebSocketTest: 2. 在program.cs中進行綁定 3. 使用websocket在線工具模擬請求:

    2024年02月03日
    瀏覽(31)
  • .Net6 Web Core API 配置 Autofac 封裝 --- 依賴注入

    .Net6 Web Core API 配置 Autofac 封裝 --- 依賴注入

    目錄 一、NuGet 包導(dǎo)入 二、Autofac 封裝類 三、Autofac 使用 四、案例測試 下列封裝 采取 程序集注入方法 , 單個依賴注入, 也適用, 可依賴注入的地方配置 Autofac Autofac.Extensions.DependencyInjection Autofac.Extras.DynamicProxy ? ?

    2024年02月14日
    瀏覽(96)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包