ABP Core 后台Angular+Ng-Zorro 图片上传

Ng-zorro upload 控件介绍 https://ng.ant.design/components/upload/zh#components-upload-demo-custom-request

官网示例效果

官网示例代码

import { Component } from ‘@angular/core‘;
import { NzMessageService, UploadFile } from ‘ng-zorro-antd‘;

@Component({
  selector: ‘nz-demo-upload-picture-card‘,
  template: `
  <div class="clearfix">
    <nz-upload
      nzAction="https://jsonplaceholder.typicode.com/posts/"
      nzListType="picture-card"
      [(nzFileList)]="fileList"
      [nzShowButton]="fileList.length < 3"
      [nzPreview]="handlePreview">
        <i nz-icon type="plus"></i>
        <div class="ant-upload-text">Upload</div>
    </nz-upload>
    <nz-modal [nzVisible]="previewVisible" [nzContent]="modalContent" [nzFooter]="null" (nzOnCancel)="previewVisible=false">
      <ng-template #modalContent>
        <img [src]="previewImage" [ngStyle]="{ ‘width‘: ‘100%‘ }" />
      </ng-template>
    </nz-modal>
  </div>
  `,
  styles: [
    `
  :host ::ng-deep i {
    font-size: 32px;
    color: #999;
  }
  :host ::ng-deep .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  `
  ]
})
export class NzDemoUploadPictureCardComponent {
  fileList = [
    {
      uid: -1,
      name: ‘xxx.png‘,
      status: ‘done‘,
      url: ‘https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png‘
    }
  ];
  previewImage = ‘‘;
  previewVisible = false;

  constructor(private msg: NzMessageService) {}

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
}

我管理端后台使用了ABP Core +Angular+Ng-Zorro (使用了52ABP基础框架 https://github.com/52ABP/LTMCompanyNameFree.YoyoCmsTemplate)

后台代码FileUploadController

public class FileUploadController : AbpController
    {

        private readonly IHostingEnvironment _hostingEnvironment;

        public FileUploadController(IHostingEnvironment hostingEnvironment)
        {
            this._hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 上传设备图片
        /// </summary>
        /// <param name="image"></param>
        /// <param name="fileName"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [RequestFormSizeLimit(valueCountLimit: 2147483647)]
        [HttpPost]
        public async Task<IActionResult> GatherImageUploadPost(IFormFile[] image, string fileName, Guid name)
        {
            string webRootPath = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            var imageName = "";
            foreach (var formFile in image)
            {
                if (formFile.Length > 0)
                {
                    string fileExt = Path.GetExtension(formFile.FileName); //文件扩展名,不含“.”
                    long fileSize = formFile.Length; //获得文件大小,以字节为单位
                    name = name == Guid.Empty ? Guid.NewGuid() : name;
                    string newName = name + fileExt; //新的文件名
                    var fileDire = webRootPath + string.Format("/Temp/Upload/","");
                    if (!Directory.Exists(fileDire))
                    {
                        Directory.CreateDirectory(fileDire);
                    }

                    var filePath = fileDire + newName;

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                    imageName = filePath.Substring(webRootPath.Length);
                }
            }

            return Ok(new { imageName });
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }

解决ASP.NET Core文件上传限制问题增加类RequestFormSizeLimitAttribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class RequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
    {
        private readonly FormOptions _formOptions;

        public RequestFormSizeLimitAttribute(int valueCountLimit)
        {
            _formOptions = new FormOptions()
            {
                ValueCountLimit = valueCountLimit
            };
        }

        public int Order { get; set; }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var features = context.HttpContext.Features;
            var formFeature = features.Get<IFormFeature>();

            if (formFeature == null || formFeature.Form == null)
            {
                // Request form has not been read yet, so set the limits
                features.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, _formOptions));
            }
        }
    }

前端代码 html代码

            <div class="clearfix">
                <nz-upload nzName="image" nzAction="{{actionUrl}}}" nzListType="picture-card" [(nzFileList)]="fileList"
                    [nzShowButton]="fileList.length < 3" [nzPreview]="handlePreview" (nzChange)="handleChange($event)">
                    <i nz-icon type="plus"></i>
                    <div class="ant-upload-text">选择设备图片</div>
                </nz-upload>
                <nz-modal [nzVisible]="previewVisible" [nzContent]="modalContent" [nzFooter]="null" (nzOnCancel)="previewVisible=false">
                    <ng-template #modalContent>
                        <img [src]="previewImage" [ngStyle]="{ ‘width‘: ‘100%‘ }" />
                    </ng-template>
                </nz-modal>
            </div>

前端代码 ts代码

 //预览
  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
  //图片上传返回
  handleChange(info: { file: UploadFile }): void {
    if (info.file.status === ‘error‘) {
      this.notify.error(‘上传图片异常,请重试‘);
    }
    if (info.file.status === ‘done‘) {
      this.getBase64(info.file.originFileObj, (img: any) => {
        // this.room.showPhoto = img;
      });
      var photo = info.file.response.result.imageName;
      this.uploadImages.push(photo);
      // alert(this.room.photo);
      this.notify.success(‘上传图片完成‘);
    }
  }
  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener(‘load‘, () => callback(reader.result));
    reader.readAsDataURL(img);
  }

最好看看效果

原文地址:https://www.cnblogs.com/Martincheng/p/10182426.html

时间: 2024-08-03 00:35:36

ABP Core 后台Angular+Ng-Zorro 图片上传的相关文章

ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)

七牛图片上传 SDK(.NET 版本):https://developer.qiniu.com/kodo/sdk/1237/csharp UpoladService示例代码: public class UpoladService : IUpoladService {     private readonly static string[] _imageExtensions = new string[] { ".jpg", ".png", ".gif&quo

layui图片上传之后后台如何修改图片的后缀名以及返回数据给前台

const pathLib = require('path');//引入node.js下的一个path模块的方法,主要处理文件的名字等工作,具体可看文档 const fs = require(''fs); var app = new express(); //前台图片上传访问路径 app.post('/upload',(req,res)=>{ if(Boolean(typeof req.files[0])){//判断访问该后台时是否有图片上传 var ext = pathLib.parse(re

简单写一下图片上传获取宽高的方法

最近,我负责的后台系统有一个图片上传校验图片比例的需求,以前没有做过这种需求,便查了一些资料总结了一下图片上传获取宽高的方法.想要获取图片的宽高首先要知道图片的url:一般图片上传UI组件或自己封装的组件都会获取到图片的url,知道url就好办了,上代码. var img_url = URL;//图片URL地址 var imgObj = new Image();//创建对象 imgObj.src = img_url;//改变图片地址 console.log(imgObj.width + "&qu

asp.net core 通过ajax上传图片及wangEditor图片上传

asp.net core 通过ajax上传图片 .net core前端代码,因为是通过ajax调用,首先要保证ajax能调用后台代码,具体参见上一篇.net core 使用ajax调用后台代码. 前端代码如下: @Html.AntiForgeryToken() @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} <div> <form id="uploadForm">

vue使用富文本编辑器vue-quill-editor实现配合后台将图片上传至七牛

一.全局注册:main.js import Vue from 'vue' import VueQuillEditor, { Quill } from 'vue-quill-editor' import { ImageDrop } from 'quill-image-drop-module' import ImageResize from 'quill-image-resize-module' import 'quill/dist/quill.core.css' import 'quill/dis

Django(十九)文件上传:图片上传(后台上传、自定义上传)、

一.基本设置 参考:https://docs.djangoproject.com/zh-hans/3.0/topics/http/file-uploads/ 1)配置project1/settings.py 因为图片也属于静态文件,所以保存到static目录下. MEDIA_ROOT=os.path.join(BASE_DIR,"static/media") 2)在static目录下创建media目录,再创建应用名称的目录,此例为app1 F:\Test\django-demo\pro

.net core CKEditor 图片上传

最近在玩 asp.net core,不想用UEditor,想使用CKEditor.故需要图片上传功能. 废话不多说,先上效果图: CKEditor 前端代码: <text id="content" name="content"></text> <script> CKEDITOR.replace('content'); </script> CKeditor config.js 配置代码:需要配置图片上传路径 CKEDIT

php相册功能实现(包含php图片上传,后台管理,浏览和删除)教程例子

相册功能实现(包含php图片上传,后台管理,浏览和删除)教程例子包括五个部分: 一.相册首页 <html> <head> <meta charset="utf-8"> <title>相册首页</title> <style> body{ width:800px; margin:0 auto; test-align:center; } </style> </head> <body>

.Net Core 图片上传FormData和Base64

缓冲和流式传输是上传文件的两种常用方案,这里主要演示流式传输. 1.Net Core MVC Form提交方式: 前端页面 form表单提交: 1 <form id="uploadForm"> 2 图片上传: <input type="file" name="file" multiple value="选择" onchange="doUpload()" id="ajaxfile&