1. 程式人生 > >ABP Core 後臺Angular+Ng-Zorro 圖片上傳

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);
  }

 

 最好看看效果