Web API 上傳下載文件

1.引用了一個第三方組件 ICSharpCode.SharpZipLib.Zip;html

2.具體代碼api

  實體類,能夠用hashtable 替代 ,感受hashtable 比較靈活瀏覽器

public class FileResult
    {
        public string FileNames { get; set; }
        public string Description { get; set; }
        public DateTime CreatedTimestamp { get; set; }
        public DateTime UpdatedTimestamp { get; set; }
        public string FileLength { get; set; }
        public string ContentTypes { get; set; }
        public string OriginalNames { get; set; }
        public string Status { get; set; }

        public string Msg { get; set; }
    }

 擴展的修改文件名稱app

 public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public WithExtensionMultipartFormDataStreamProvider(string rootPath)
            : base(rootPath)
        {

        }
        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
            return Guid.NewGuid().ToString() + extension;
        }

        private string GetValidFileName(string filePath)
        {
            char[] invalids = System.IO.Path.GetInvalidFileNameChars();
            return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
        }
    }

具體上傳類ide

public class UpLoadController : ApiController
    {
        private const string UploadFolder = "uploads";

        [HttpPost]
        public Task<IQueryable<FileResult>> UpLoadFile()
        {
            try
            {
                string uploadFolderPath = HostingEnvironment.MapPath("~/" + UploadFolder);

                //若是路徑不存在,建立路徑
                if (!Directory.Exists(uploadFolderPath))
                    Directory.CreateDirectory(uploadFolderPath);
                if (Request.Content.IsMimeMultipartContent())
                {
                    var streamProvider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath);
                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IQueryable<FileResult>>(t =>
                    {
                        if (t.IsFaulted || t.IsCanceled)
                        {
                            throw new HttpResponseException(HttpStatusCode.InternalServerError);
                        }
                        var fileInfo = streamProvider.FileData.Select(i =>
                        {
                            var info = new FileInfo(i.LocalFileName);
                            return new FileResult()
                            {
                                FileNames = info.Name,
                                Description = "描述文本",
                                ContentTypes = info.Extension.ToString(),
                                CreatedTimestamp = info.CreationTime,
                                OriginalNames = info.Name.ToString(),
                                FileLength = info.Length.ToString()
                            };
                        });
                        return fileInfo.AsQueryable();
                    });

                    return task;
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
                }
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }

        [HttpGet]
        public HttpResponseMessage DownloadFile(string fileName)
        {
            HttpResponseMessage result = null;

            DirectoryInfo directoryInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/" + UploadFolder));
            FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault();
            if (foundFileInfo != null)
            {
                FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open);

                result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(fs);
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name;
            }
            else
            {
                result = new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }

        /// <summary>  
        /// 壓縮文件下載  
        /// </summary>  
        /// <param name="fileIds">文件編號</param>  
        /// <returns></returns>  
        [HttpGet]
        public HttpResponseMessage DownLoad(string fileIds)
        {
            string customFileName = DateTime.Now.ToString("yyyyMMddHHmmss")+ ".zip";//客戶端保存的文件名
            string path = HostingEnvironment.MapPath("~/" + UploadFolder + "/" );
            HttpResponseMessage response = new HttpResponseMessage();
            try
            {
                string[] filenames = { "4c301d70-a681-46bd-88c1-97a133ee4b79.png", "4648cac5-d15f-45f2-9b06-7a2eebf5c604.jpg" };
                using (ZipOutputStream s = new ZipOutputStream(File.Create(path+"/"+ customFileName)))
                {
                    s.SetLevel(9);
                    byte[] buffer = new byte[4096];

                    foreach (string file in filenames)
                    {
                        var entry = new ZipEntry(Path.GetFileName(path+"/"+file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(path + "/" + file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
                FileStream fileStream = new FileStream(path + "/" + customFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                response.Content = new StreamContent(fileStream);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = customFileName;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  // 這句話要告訴瀏覽器要下載文件  
                response.Content.Headers.ContentLength = new FileInfo(path + "/" + customFileName).Length;
            }
            catch (Exception ex)
            {

            }
            return response;
        }

        /// <summary>
        /// 圖片上傳  [FromBody]string token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Task<IQueryable<Hashtable>> ImgUpload()
        {
            string status = "0";
            string msg = "";
            const int maxSize = 10000000;
            const string fileTypes = "gif,jpg,jpeg,png,bmp";
            bool isthumb = true;//是否生成縮略圖
            string PrefixThumbnail = "thumb_"; //隨機生成縮略圖文件名前綴
            string daypath=DateTime.Now.ToString("yyyyMMdd");

            // 檢查是不是 multipart/form-data 
            if (!Request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            // 文件保存目錄路徑 
            string uploadFolderPath = HostingEnvironment.MapPath("~/" + UploadFolder+ "/"+ daypath);
            //檢查上傳的物理路徑是否存在,不存在則建立
            if (!Directory.Exists(uploadFolderPath))
            {
                Directory.CreateDirectory(uploadFolderPath);
            }
            var streamProvider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath);
            //var streamProvider =  new MultipartFormDataStreamProvider(uploadFolderPath);

            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IQueryable<Hashtable>>(t =>
            {

                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                var fileInfo = streamProvider.FileData.Select(i =>
                {

                    var info = new FileInfo(i.LocalFileName);

                        //原始上傳名稱
                        LogHelper.writeLog(i.Headers.ContentDisposition.FileName);
                    string orfilename = GetOrginFileName(i.Headers.ContentDisposition.FileName);

                    if (info.Length <= 0)
                    {
                        status = "0";
                        msg = "請選擇上傳文件";
                    }
                    else if (info.Length > maxSize)
                    {
                        status = "0";
                        msg = "上傳文件大小超過限制";
                    }
                    else
                    {
                        var fileExt = info.Extension.ToString();
                        if (String.IsNullOrEmpty(fileExt) ||
                            Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                        {
                            status = "0";
                            msg = "不支持上傳文件類型";
                        }
                        else
                        {
                            status = "1";
                            msg = "上傳成功";
                            //生成縮略圖
                            if (isthumb) { 
                            MakeThumbnailImage(uploadFolderPath + "/" + info.Name, uploadFolderPath + "/" + PrefixThumbnail + info.Name, 300, 300, "Cut");
                            }
                        }
                    }
                    Hashtable hs = new Hashtable();
                    hs["status"] = status;
                    hs["msg"] = msg;
                    hs["filename"] = "/"+ UploadFolder + "/"+ daypath +"/"+ info.Name;
                    hs["orginname"] = orfilename;
                    return hs;
                });
                return fileInfo.AsQueryable();
            });

            return task;
        }

        private string GetOrginFileName(string filePath)
        {
            string result = "";
            try
            {
                var filename = Regex.Match(filePath, @"[^\\]+$");
                result = filename.ToString().Replace("\"", "");
            }
            catch (Exception)
            { }
            return result;
        }

        /// <summary>
        /// 生成縮略圖
        /// </summary>
        /// <param name="fileName">源圖路徑(絕對路徑)</param>
        /// <param name="newFileName">縮略圖路徑(絕對路徑)</param>
        /// <param name="width">縮略圖寬度</param>
        /// <param name="height">縮略圖高度</param>
        /// <param name="mode">生成縮略圖的方式</param>    
        private void MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(fileName);
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高寬縮放(補白)
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    else
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    break;
                case "W"://指定寬,高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高,寬按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高寬裁減(不變形)                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一個bmp圖片
            Bitmap b = new Bitmap(towidth, toheight);
            try
            {
                //新建一個畫板
                Graphics g = Graphics.FromImage(b);
                //設置高質量插值法
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                //設置高質量,低速度呈現平滑程度
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                //清空畫布並以透明背景色填充
                g.Clear(Color.White);
                //g.Clear(Color.Transparent);
                //在指定位置而且按指定大小繪製原圖片的指定部分
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

                SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                b.Dispose();
            }
        }

        /// <summary>
        /// 保存圖片
        /// </summary>
        /// <param name="image">Image 對象</param>
        /// <param name="savePath">保存路徑</param>
        /// <param name="ici">指定格式的編解碼參數</param>
        private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
        {
            //設置 原圖片 對象的 EncoderParameters 對象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }
        /// <summary>
        /// 獲取圖像編碼解碼器的全部相關信息
        /// </summary>
        /// <param name="mimeType">包含編碼解碼器的多用途網際郵件擴充協議 (MIME) 類型的字符串</param>
        /// <returns>返回圖像編碼解碼器的全部相關信息</returns>
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType)
                    return ici;
            }
            return null;
        }

        /// <summary>
        /// 獲得圖片格式
        /// </summary>
        /// <param name="name">文件名稱</param>
        /// <returns></returns>
        public static ImageFormat GetFormat(string name)
        {
            string ext = name.Substring(name.LastIndexOf(".") + 1);
            switch (ext.ToLower())
            {
                case "jpg":
                case "jpeg":
                    return ImageFormat.Jpeg;
                case "bmp":
                    return ImageFormat.Bmp;
                case "png":
                    return ImageFormat.Png;
                case "gif":
                    return ImageFormat.Gif;
                default:
                    return ImageFormat.Jpeg;
            }
        }
    }

3.示例代碼post

<form name="form1" method="post" enctype="multipart/form-data" action="http://localhost:4589/api/UpLoad/ImgUpload">

        <input type="file" name="file1" style="width:160px;" />
        <input type="file" name="file2" style="width:160px;" />
        <input type="submit" name="Submit" value="添加" />
    </form>
	<img src=""  id='testimg'/>
	<a href='http://192.168.0.108:8010/api/UpLoad/DownloadFile?fileName=4648cac5-d15f-45f2-9b06-7a2eebf5c604.png'>download</a>
	<a href='http://192.168.0.108:8010/api/UpLoad/DownLoad?fileIds=2'>downloadzip</a>
相關文章
相關標籤/搜索