首页 > 其他分享 >Vue3+axios+.Net使用分片上传

Vue3+axios+.Net使用分片上传

时间:2024-05-19 21:08:04浏览次数:13  
标签:file axios name ajaxResponse +. key Vue3 input 上传

Vue3+axios+.Net使用分片上传

前端代码

在ApiService.cs中增加方法

//上传文件
public static async uploadFile(file){
  const chunkSize = 1024 * 1024; // 1MB 每1mb分片
  const totalChunks = Math.ceil(file.size / chunkSize);
  let key='';

  let tag=true;
  let url='';//文件上传的结果
  for (let i = 0; i < totalChunks; i++) {
    if (!tag){
      continue;
    }
    const start = i * chunkSize;
    const end = Math.min(file.size, start + chunkSize);
    const chunk = file.slice(start, end);

    // Create FormData object and append chunk data
    const formData = new FormData();
    formData.append('file', chunk, file.name);
    formData.append('name', file.name);
    formData.append('key', key);
    formData.append('chunk', i.toString());
    formData.append('chunks', totalChunks.toString());

    // Make POST request using Axios
    await axios.post('/api/test/files', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(({ data }) => {
      key = data.key as string;
      if (i == (totalChunks-1)){
        if (import.meta.env.VITE_APP_API_URL != "/") {
          url = import.meta.env.VITE_APP_API_URL + data.url;
        } else {
          url = data.url;
        }
      }
      // console.log(data);
    }).catch(f=>{
      tag=false;
    });
  }
  return {success:tag,url:url};
}

使用如下

//将上传文件传入
let result = await ApiService.uploadFile(data);
if (data.success) {
  //上传成功,并返回了文件路径
  value.value = data.url;
    
} else {
  swalMessage.error("上传失败")
}

后端代码

public virtual ActionResult Plupload(PluploadInputDto input)
{
    AjaxResponse ajaxResponse = new AjaxResponse(false);
    //过滤文件名的异常字符,只能剩余中文字母及数字,防止恶意攻击()
    input.name = StringHelper.SafeSearchStrFileName(input.name, "_");

    //根据文件后缀判断是否在允许上传格式中
    if (!allowFileExt.Contains(Path.GetExtension(input.name).ToLower().Replace(".", string.Empty))) { return Json(ajaxResponse); }
    //每个用户一个文件夹
    string uid = HttpContext.User.Identity.Name.ToUpper().ToMd5();
    string returnPath = "";

    //再次处理文件名
    input.name = StringHelper.SafeSearchStrFileName(Path.GetFileNameWithoutExtension(input.name), "_") + Path.GetExtension(input.name);

    if (input.file == null)
    {
        return Json(ajaxResponse);
    }
    
    string basePath = "/assets/userfiles/{0}/temp/".FormatWith(uid);
    string path = _env.WebRootPath +basePath;
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

    if (input.chunks == 1)
    {
        //单个上传
        //重新生成文件名,防止文件重复
        input.name = Guid.NewGuid().ToString("n") + input.name;
        string fileNamePath = path + input.name;
        using (FileStream stream = new FileStream(fileNamePath, FileMode.Create))
        {
            input.file.CopyTo(stream);
        }

        ajaxResponse.Success = true;
        ajaxResponse.Result = new { url= Url.Content("~"+basePath+input.name)};
        return Json(ajaxResponse);
    }
    else
    {
        //多个分片上传
        var key = Guid.NewGuid().ToString("n");
        if (input.chunk==0)
        {
            input.name = key + input.name;
            string fileNamePath = path + input.name;
            using (FileStream stream = new FileStream(fileNamePath, FileMode.Create))
            {
                input.file.CopyTo(stream);
            }
            ajaxResponse.Success = true;
            ajaxResponse.Result = new { key=key };
            return Json(ajaxResponse);
        }
        else
        {
            //第一次以后的上传
            if (!input.key.IsGuid())
            {
                return Json(ajaxResponse);
            }

            key=input.key;
            input.name = input.name + ".bak";
            input.name = input.key + input.name;
            string fileNamePath = path + input.name;
            if (!System.IO.File.Exists(fileNamePath))
            {
                return Json(ajaxResponse);
            }
            using (FileStream stream = new FileStream(fileNamePath, FileMode.Append))
            {
                input.file.CopyTo(stream);
            }

            if (input.chunk == (input.chunks-1))
            {
                //最后的上传成功
                var name2=input.name.Substring(0, input.name.Length - 4);
                System.IO.File.Move(fileNamePath,path + name2);
                
                ajaxResponse.Success = true;
                ajaxResponse.Result = new { url= Url.Content("~"+basePath+name2)};
                return Json(ajaxResponse);
            }
            else
            {
                ajaxResponse.Success = true;
                ajaxResponse.Result = new { key=key };
                return Json(ajaxResponse);
            }
        }
    }
}

标签:file,axios,name,ajaxResponse,+.,key,Vue3,input,上传
From: https://www.cnblogs.com/itljf/p/18200766

相关文章

  • Vue3报错:已声明“upperName”,但从未读取其值。ts-plugin(6133)
    Vue3报错:已声明“upperName”,但从未读取其值。ts-plugin(6133)报错显示:类型“StoreToRefs<Store<"count",{sum:number;name:string;address:string;},{},{increment(value:number):void;}>>”上不存在属性“upperName”。ts-plugin(2339)相关代码:vue文件:con......
  • VUE速通(10)Vue3核心语法(2)setup
    1setup概述setup是Vue3中一个新的配置项,值是一个函数,它是CompositionAPI“表演的舞台”,组件中所用到的:数据、方法、计算属性、监视......等等,均配置在setup中。特点如下:setup函数返回的对象中的内容,可直接在模板中使用。setup中访问this是undefined。setup函数会......
  • VSCode安装vue3插件
    1.以前的volar已经弃用了。2.最近vue插件 3.安装好插件后,在vscode中创建项目可能会报错。解决方法:1.使用window+r调出cmd,运行node-v,npm-v都没问题。那么尝试以管理员方式运行vscode,如果还是不行,重启一下电脑。2.网络原因,网络波动或者网比较差的时候导致下载丢包,把node......
  • 基于uniapp+vue3自定义增强版table表格组件「兼容H5+小程序+App端」
    vue3+uniapp多端自定义table组件|uniapp加强版综合表格组件uv3-table:一款基于uniapp+vue3跨端自定义手机端增强版表格组件。支持固定表头/列、边框、斑马纹、单选/多选,自定义表头/表体插槽、左右固定列阴影高亮显示。支持编译兼容H5+小程序端+App端。如下图:H5+小程序+App端,多端......
  • vue3+vite,写动态路由时候遇到的坑
    import导入一直报错,看了网上说import不行要写成 require之类的,都试了个遍,结果还是不行。一个很容易犯的错误:理所当然的以为alias是可以使用的。事实上写全相对路径就可以了!!! letr=awaitapis['common/getRouteList']()constlist=r.map((t)=>({id:t.id,pid......
  • vuejs3.0 从入门到精通——vite+vue3+ts 显示找不到模块“../views/HomeView.vue”或
    vite+vue3+ts显示找不到模块“../views/HomeView.vue”或其相应的类型声明。ts(2307)一、在根目录下的env.d.ts文件(没有就自己创建)二、在env.d.ts文件中添加以下代码declaremodule'*.vue'{importtype{DefineComponent}from'vue'constcomponent:DefineCo......
  • vue3 ts 集成 tinymce
    首先引入@tinymce/tinymce-vueyarnadd@tinymce/tinymce-vue-S我的版本是然后写一个组件<template><mainid="sample"><Editorv-model="editorData"api-key="j7tvgx4xnptg3cjd63cfnl62z9s78uylw4o7vkkwdljjy91e":init=&qu......
  • Vue3:Cannot read properties of null (reading 'isCE')
    Cannotreadpropertiesofnull(reading'isCE')  这个问题是在vue3中引入elementui的列表框时出现的。经过网上查询,有说是装了两个vue版本的,也有说是其他代码写错导致的,还有说是导入错误的。  但我的不是这个问题,我的是版本兼容问题。因为在网上查询时看到,elementui适......
  • 基于Vue3水印组件封装:防篡改守护!
    基于Vue3的全新水印通用组件。这款组件不仅功能强大,而且易于集成,能够轻松为您的网页或应用添加自定义水印,有效防止内容被篡改或盗用。在线查看效果:原文可查看效果地址一,编写watermark组件<template><divref="watermarkContainerRef"class="watermark-container">......
  • vue3百科全书
    @目录2.2.【基于vite创建】(推荐)2.3.【一个简单的效果】3.Vue3核心语法3.1.【OptionsAPI与CompositionAPI】3.2.【拉开序幕的setup】setup概述setup的返回值setup与OptionsAPI的关系setup语法糖3.3.【ref创建:基本类型的响应式数据】3.4.【reactive创建:对象......