zoukankan      html  css  js  c++  java
  • NCF 如何在Xncf页面表单中使用上传功能

    简介

    使用后台,搭建后台功能,非常必要的功能就是上传功能,那么结合NCF如何使用表单上传呢,下面让我来介绍一下哈

    资源

    element-ui upload:https://element.eleme.io/#/zh-CN/component/upload#methods

    vue 方法:https://cn.vuejs.org/v2/guide/events.html#%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86%E6%96%B9%E6%B3%95

    步骤

    1.在页面表单中加入上传控件

    2.在js页面中加入处理上传的逻辑方法

    3.服务端来处理接收到的文件信息

      3-1.通过后台本身的.cs文件来处理接受文件

      3-2.通过接口来上传文件(本文介绍的)

    实施

    1.在表单中(即在xxx.cshtml文件中)添加element ui 中的 el-upload 控件,代码如下

    <el-form-item label="封面图">
        <el-upload action="https://localhost:44311/api/v1/common/upload" 
              list
    -type="picture-card"
              show
    -file-list="true"
              accept
    ="image/png, image/jpeg"
              :on
    -success="uploadSuccess"
              :on
    -error="uploadError"
              :on
    -preview="handlePictureCardPreview"
              :on
    -remove="handleRemove">
          <i class="el-icon-plus"></i>
          <div class="el-upload__tip" slot="tip">不能超过100MB</div>
      </el-upload>
      <img width="100%" :src="dialogImageUrl" alt="">
      <el-input class="hidden" v-model="dialog.data.cover" clearable placeholder="封面图" />
    </el-form-item>

    2.在js文件中增加处理上传控件的逻辑方法

    handleRemove(file, fileList) {
        console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    },
    uploadSuccess(res, file, fileList) {
        // 上传成功
        this.fileList = fileList;
        console.log("上传成功" + fileList.length);
        console.log(JSON.stringify(res));
    
        if (res.code == 200) {
            this.$notify({
                title: '成功',
                message: '恭喜你,上传成功',
                type: 'success'
            });
            this.dialog.data.cover = res.data;
        }
        else {
            this.$notify.error({
                title: '失败',
                message: '上传失败,请重新上传'
            });
        }
    },
    uploadError() {
        //this.refs.upload.clearFiles();
        this.$notify.error({
            title: '失败',
            message: '上传失败,请重新上传'
        });
    },

    3.服务端接口接收文件的方法

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">文件信息</param>
    /// <returns></returns>
    [HttpPost]
    public IActionResult Upload([FromForm] IFormFile file)
    {
        string prefixPath = string.Empty;
        try
        {
            var file_data = this.Request.Form.Files[0];
            if (file_data == null)
            {
                return Fail("文件参数无效,请提供name值为file_data的文件");
            }
            //验证文件扩展名
            var extension = Path.GetExtension(file_data.FileName);
            if (!AllowFileExtension.FileExtension.Contains(extension))
            {
                return Fail("不支持此扩展名文件的上传!");
            }
            //基础存储路径
            var basePath = "default"; // sysKeyModel.Name;
            //验证文件前缀路径有效性
            if (!string.IsNullOrWhiteSpace(prefixPath))
            {
                if (prefixPath.IndexOfAny(Path.GetInvalidPathChars()) > -1)//验证路径有效性
                {
                    return Fail("无效路径!");
                }
                //进一步规范路径
                var invalidPattern = new Regex(@"[\/:*?42<>|]");
                prefixPath = invalidPattern.Replace(prefixPath, "");
    
                prefixPath = prefixPath.Replace("_", "\");//使用下划线“_”代替斜杠“”
                basePath = Path.Combine(basePath, prefixPath);
            }
            //物理文件路径
            var pathMp = Path.Combine(_webHostEnvironment.ContentRootPath, staticResourceSetting.CurrentValue.RootDir, basePath);
            if (!Directory.Exists(pathMp)) Directory.CreateDirectory(pathMp);
    
            string strFileName = file_data.FileName.Split('\').LastOrDefault();
    
            var filename = $"{DateTime.Now:yyyyMMddHHmmss}-{UniqueHelper.LongId()}{extension}";
            string strFileHash = string.Empty;
            string strFilePath = string.Empty;
            using (var fs = new FileStream(Path.Combine(pathMp, filename), FileMode.CreateNew))
            {
                file_data.CopyTo(fs);
                strFileHash = HashHelper.SHA1File(fs);//赋值文件Hash值
                fs.Flush();
            }
            ////物理文件路径(斜杠)转换为URL路径(反斜杠)
            strFilePath = $"https://localhost:44311/static/default/{filename}";
            return Success(strFilePath);
        }
        catch (Exception ex)
        {
            return Fail(ex.Message);
        }
    }

    如果你已经动手走到这里了,那么恭喜你,你完成上传功能了。

    不清楚的地方,再问我

    关注我的博客,了解更多NCF的实用功能

  • 相关阅读:
    人工智能背后的故事
    idea 开发插件。
    安卓工作室 Android studio 或 Intellij IDEA 美化 修改 汉化 酷炫 装逼 Android studio or Intellij IDEA beautify modify Chinesization cool decoration
    安卓工作室 android studio文件和代码模板,以及汉化出错问题
    安卓工作室 android studio 汉化后,报错。 设置界面打不开。Can't find resource for bundle java.util.PropertyResourceBundle, key emmet.bem.class.name.element.separator.label
    android studio的汉化 教程 及解析
    安卓工作室Android Studio 快捷键
    安卓工作室 android studio 的 汉化 美化 定制 Android studio's Chinesization beautification customization
    VR开发 VR development
    Lakeshore 中文开发界面,示例项目,飞机大战 等 Lakeshore Chinese development interface, sample project, aircraft war, etc
  • 原文地址:https://www.cnblogs.com/zhao365845726/p/13806596.html
Copyright © 2011-2022 走看看