C# Web Api 上傳文件

1、 使用默認方法上傳文件:html

一、Action:web

 /// <summary>
        /// 上傳文件 使用上傳後的默認文件名稱
        /// 默認名稱是BodyPart_XXXXXX,BodyPart_加Guid碼
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Upload")]
        public async Task<string> Upload()
        {
            try
            {
                //web api 獲取項目根目錄下指定的文件下
                var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images");
                var provider = new MultipartFormDataStreamProvider(root);
                
                //文件已經上傳  可是文件沒有後綴名  須要給文件添加後綴名
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (var file in provider.FileData)
                {
                    //這裏獲取含有雙引號'" '
                    string filename = file.Headers.ContentDisposition.FileName.Trim('"');
                    //獲取對應文件後綴名
                    string fileExt = filename.Substring(filename.LastIndexOf('.'));
                    
                    FileInfo fileinfo = new FileInfo(file.LocalFileName);
                    //fileinfo.Name 上傳後的文件路徑 此處不含後綴名 
                    //修改文件名 添加後綴名
                    string newFilename = fileinfo.Name + fileExt;
                    //最後保存文件路徑
                    string saveUrl = Path.Combine(root, newFilename);
                    fileinfo.MoveTo(saveUrl);
                }
                return "success";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

二、html模擬代碼:api

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <h1>檸檬夥伴雲</h1>
    <form action="/Test/Upload" method="post" enctype="multipart/form-data">

        <input type="file" name="f1"  /> <br /><br />
        <input type="file" name="f2" /> <br /><br />
   
        <input type="submit"  value="上傳圖片" /> 
        
    </form>
</body>
</html>

三、效果以下圖:服務器

 

上圖就是上傳後文件沒有後綴名效果async

對第一張沒有後綴名添加後綴名的效果ide

 

2、修改上傳文件後綴名post

一、action:ui

 

/// <summary>
        /// 上傳文件 修改上傳文件名稱 也不包含後綴名
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Upload2")]
        public async Task<string> Upload2()
        {
            try
            {
                //web api 獲取項目根目錄下指定的文件下
                var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images");
                //對上傳文件從新命名 根據需求對應修改文件名稱 不包含後綴名 只是前綴名
                var provider = new RenamingMultipartFormDataStreamProvider(root);

                //文件已經上傳  可是文件沒有後綴名  須要給文件添加後綴名
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (var file in provider.FileData)
                {
                    //這裏獲取含有雙引號'" '
                    string filename = file.Headers.ContentDisposition.FileName.Trim('"');
                    //獲取對應文件後綴名
                    string fileExt = filename.Substring(filename.LastIndexOf('.'));

                    FileInfo fileinfo = new FileInfo(file.LocalFileName);
                    //fileinfo.Name 上傳後的文件路徑 此處不含後綴名 
                    //修改文件名 添加後綴名
                    string newFilename = fileinfo.Name + fileExt;
                    //最後保存文件路徑
                    string saveUrl = Path.Combine(root, newFilename);
                    fileinfo.MoveTo(saveUrl);
                }
                return "success";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

二、RenamingMultipartFormDataStreamProvider 類:spa

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;

namespace Test.One.Common
{
    public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        /// <summary>
        /// 文件重命名
        /// </summary>
        /// <param name="root"></param>
        public RenamingMultipartFormDataStreamProvider(string root)
            : base(root)
        {
        }
        /// <summary>
        /// 文件重命名
        /// </summary>
        /// <param name="headers"></param>
        /// <returns></returns>
        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            string fileName = headers.ContentDisposition.Name;
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                fileName = Guid.NewGuid().ToString();
            }
            return fileName.Replace("\"", string.Empty);
        }
    }
}

 

三、html 模擬代碼:3d

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <h1>檸檬夥伴雲</h1>
    <form action="/Test/Upload2" method="post" enctype="multipart/form-data">

        <input type="file" name="f1"  /> <br /><br />
        <input type="file" name="f2" /> <br /><br />
   
        <input type="submit"  value="上傳圖片" /> 
        
    </form>
</body>
</html>

三、效果:

 

實例二:

api:

   /// <summary>
        /// TestFile
        /// </summary>
        /// <returns></returns>
        [HttpPost,Route("TestFile")]
        public async Task<Result<bool>> TestFile()
        {
            Result<bool> result = new Result<bool>();
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    result.ReturnCode = ResultCode.InvalidParam;
                    result.Data = false;
                    result.ReturnMsg = "請求數據不是multipart/form-data類型";
                    return result;
                }

                string root = HostingEnvironment.MapPath("/Resources/Templet/");
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string resourcePath  = Path.Combine(root, date);
                if (!Directory.Exists(resourcePath))
                {
                    Directory.CreateDirectory(resourcePath);
                }

                var provider = new RenamingMultipartFormDataStreamProvider(resourcePath);
                // 接收數據,並保存文件
                var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);

                if (bodyparts.FormData.Count <= 0 || provider.FileData == null && !provider.FileData.Any())
                {
                    result.ReturnCode = ResultCode.InvalidParam;
                    result.Data = false;
                    result.ReturnMsg = "文件或參數不全,視頻上傳失敗。";
                    return result;
                }

                UploadContactListFileModel uploadModel = new UploadContactListFileModel();

                if (bodyparts.FormData.AllKeys.Contains("ContactListName"))
                {
                    uploadModel.ContactListName = bodyparts.FormData["ContactListName"];
                }

                foreach (MultipartFileData file in provider.FileData)
                {
                    //上傳的文件名
                    string name = file.Headers.ContentDisposition.FileName.Replace("\"", "");
                    string extension = Path.GetExtension(name);
                    if (extension == ".csv" || extension == ".xls" || extension == ".xlsx")
                    {
                        //修改文件名
                        string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name);
                        string uploadPath = Path.Combine(resourcePath, newFileName);
                        //保存文件
                        File.Move(file.LocalFileName, uploadPath);
                        uploadModel.FilePath = uploadPath;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                result.ReturnMsg = "服務器內部發生異常";
                Logger.Error("SelfsController[AddVideos]", ex);
            }
            return result;
        }

model:

 public class UploadContactListFileModel
    {
        
        /// <summary>
        /// FilePath
        /// </summary>
        public string FilePath { get; set; }

        /// <summary>
        /// ContactListName
        /// </summary>
        public string ContactListName { get; set; }

        /// <summary>
        /// IsError
        /// </summary>
        /// <returns></returns>
        public bool IsError()
        {
            return string.IsNullOrEmpty(FilePath) || string.IsNullOrEmpty(ContactListName);
        }
    }

html:

  <form action="/Spread/External/TestFile" method="post" enctype="multipart/form-data">
            <input type="text" name="ContactListName" value="ContactListName" /> <br />
            <input type="file" name="upload" value="" /><br />
            <input type="submit" name="name" value="上傳" />
        </form>
相關文章
相關標籤/搜索