2019年6月26日 星期三

Web API Upload file example(C#)

Web API Upload file example.




Client side (angular)

import { Observable, throwError } from 'rxjs';
import { environment } from 'src/environments/environment.prod';
import { Injectable, ErrorHandler } from '@angular/core';
import { HttpRequest, HttpEventType, HttpClient } from '@angular/common/http';
import { clsAuth } from './cls-auth';
import { clsAlert } from './cls-alert';

@Injectable({
    providedIn: 'root'
})
export class clsFileUpload {
    public progress: number;
    public message: string;

    constructor(
        private http: HttpClient,
        private auth: clsAuth,
        private alert: clsAlert
    ) { }

    uploadImage(file: File, filename: string):boolean {
        let ret = false;
        try {
            if (file.size === 0)
                return true;

            var re = /\.(jpg|gif|png)$/i;  //允許的圖片副檔名 
            if (!re.test(file.name)) {
                alert("只允許上傳JPG或GIF影像檔");
                return ret;
            }

            const formData = new FormData();
            formData.append('file', file, filename);
            this.http.post(
                `${environment.baseUrl}/files/uploadfile`,
                formData, {
                    reportProgress: true,
                    observe: 'events'
                }).subscribe(
                    (res) => {
                        console.log(res);
                        ret = true;
                    },
                    (err) => {
                        console.log(err)
                        this.alert.showErrorMessage(err.message);
                    }
                );
        }
        catch (e) {
            console.log(e);
        }
        return ret;
    }
}






Server side (C#)

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

using mshr2019.App_Class.Sys_Class;

namespace mshr2019.Controllers {

    [RoutePrefix("files")]
    public class UploadController : clsApiController {
        private clsLog _cLog = new clsLog();

        [Route("uploadfile")]
        [HttpPost]
        [ValidateMimeMultipartContentFilter]
        public async Task UploadSingleFile() {
            bool ret = false;
            try {
                List listMsg = new List();
                HttpFileCollection files = HttpContext.Current.Request.Files;
                #region Check
                if (files.Count <= 0)
                    listMsg.Add("請先選擇要上傳的檔案。");

                for (int i = 0; i < files.Count; i++) //逐一檢查
                {
                    HttpPostedFile aFile = files[i];
                    if (aFile.ContentLength == 0 || String.IsNullOrEmpty(aFile.FileName))
                        continue;

                    if (aFile.ContentLength > _file_max_size)
                        listMsg.Add("檔案大小超出系統限制(" + (_file_max_size / 1000000.0).ToString() + "Mb)。[" + aFile.FileName + "]");

                    bool ispass = false;
                    foreach (string s in _file_ext.Split(',')) {
                        if (Path.GetExtension(aFile.FileName).ToLower() == s.Trim().ToLower()) {
                            ispass = true;
                            break;
                        }
                    }

                    if (!ispass)
                        listMsg.Add("檔案副檔名被系統限制,無法上傳。[" + aFile.FileName + "]");
                }

                if (listMsg.Count > 0) {
                    string sM = "";
                    foreach (string s in listMsg)
                        sM += s + Environment.NewLine;
                    throw new Exception(sM);
                }
                #endregion
                string sPath = _cFunc.getUploadFilePath("employee", "photo");                
                try {
                    for (int i = 0; i < files.Count; i++) //逐一上傳
                    {
                        HttpPostedFile f = files[i];    //File
                        string sPathFile = Path.GetFileName(f.FileName).Replace("(", "");
                        f.SaveAs(string.Format(@"{0}\{1}", sPath, sPathFile));//上傳
                        _cLog.RjWriteEventLog("上傳檔案: " + f.FileName);
                    }
                    ret = true;
                } catch (Exception ex) {
                    //刪除本次上傳中已完成上傳的檔案
                    for (int i = 0; i < files.Count; i++) //逐一上傳
                    {
                        HttpPostedFile f = files[i];    //File
                        string sPathFile = Path.GetFileName(f.FileName).Replace("(", "");
                        string fname = string.Format(@"{0}\{1}", sPath, sPathFile);
                        if (File.Exists(fname)) {
                            File.Delete(fname);
                            _cLog.RjWriteEventLog("刪除檔案: " + fname);
                        }
                    }
                    throw new Exception(ex.Message, ex);
                }
            } catch (Exception ex) {
                _cLog.RjWriteEventLog(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            return ret;
        }
    }

    public class ValidateMimeMultipartContentFilter : ActionFilterAttribute {
        public override void OnActionExecuting(HttpActionContext actionContext) {
            if (!actionContext.Request.Content.IsMimeMultipartContent()) {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {

        }

    }

    public class FileResult {
        public IEnumerable FileNames { get; set; }
        public IEnumerable ContentTypes { get; set; }
        public IEnumerable Names { get; set; }
        public string Description { get; set; }
        public DateTime CreatedTimestamp { get; set; }
        public DateTime UpdatedTimestamp { get; set; }
        public string DownloadLink { get; set; }
    }
}

沒有留言:

張貼留言