Api上傳下載Helper輔助類

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    public class FileOperationController : ApiController
    {
        // 允許上傳的文件擴展名
        public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png" };

        public string UrlPath = "/FileUpload/";
        [HttpGet]
        public void DownLoad(string Url)
        {
            string filePath = HttpContext.Current.Server.MapPath(Url);
            FileInfo fi = new FileInfo(filePath);
            if (File.Exists(filePath))
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearHeaders();
                response.ClearContent();
                response.Buffer = true;
                response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fi.Name));
                response.Charset = "GB2312";
                response.ContentEncoding = Encoding.GetEncoding("GB2312");
                response.ContentType = MimeMapping.GetMimeMapping(fi.Name);
                response.WriteFile(filePath);
                response.Flush();
                response.Close();
            }
        }
        [HttpPost]
        public FileResult UpLoad()
        {
            var request = HttpContext.Current.Request;
            if (request.Files.Count > 0)
            {
                var file = request.Files[0];
                var extenfilename = Path.GetExtension(file.FileName);

                string path = HttpContext.Current.Server.MapPath(UrlPath);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                if (ExtentsfileName.Contains(extenfilename.ToLower()))
                {
                    string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
                    string filepath = HttpContext.Current.Server.MapPath(urlfile);
                    file.SaveAs(filepath);
                    return new FileResult() { Code = 0, Msg = "上傳成功", Url = urlfile };
                }
                else
                {
                    return new FileResult() { Code = -1, Msg = "只允許上傳指定格式文件"+string.Join(",",ExtentsfileName), Url = "" };
                }
            }
            else
            {
                return new FileResult() { Code = -1, Msg = "不能上傳空文件", Url = "" };
            }
        }
    }

    public class FileResult
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public string Url { get; set; }
    }
}



//<input type = "file" id="f1" />
//<input type = "button" value="aa" οnclick="ff()"/>

//< script >
//    function ff()
//{
//    var formData = new FormData();
//    var file = document.getElementById("f1").files[0];
//    formData.append("fileInfo", file);
//        $.ajax({
//    url: "https://localhost:44370/api/FileOperation/UpLoad",
//            type: "POST",
//            data: formData,
//            contentType: false,//必須false纔會自動加上正確的Content-Type
//            processData: false,//必須false纔會避開jQuery對 formdata 的默認處理,XMLHttpRequest會對 formdata 進行正確的處理
//            success: function(data) {
//            if (data.Code < 0)
//                alert(data.Msg)
//                else
//                alert(data.Url)
//            },
//            error: function(data) {
//            alert("上傳失敗!");
//        }
//    });
//}

//</script>


//<a href = "https://localhost:44370/api/FileOperation/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下載 </ a >
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章