1. 程式人生 > >.NET企業級應用WebService上傳下載文件

.NET企業級應用WebService上傳下載文件

directory 寫入文件 index ret eno viewbag dex tdi 添加

在建立好一個WebService後會有一個自帶的

 [WebMethod]//在待會寫的所有方法中都要寫這個,便於調試
        public string HelloWorld()
        {
            return "Hello World";
        }

現在可以試一下錄入記錄

 [WebMethod]
        public UserInfo Login(string userName, string pwd)
        {
            if (userName == "admin" && pwd == "123
") { return new UserInfo() { UserName="admin",Pwd="",Age=50,Remark="我很帥" }; } else { return null; } }

在MVC項目中的控制器中調用

//第一步:添加服務引用
        //實例化服務引用:服務對象以SoapClient
        MyWebServiceSoapClient client = new
MyWebServiceSoapClient(); public ActionResult Index() { string result = client.HelloWorld(); Response.Write(result); return View(); }

[WebMethod]
public UserInfo Login(string userName, string pwd)
{
if (userName == "admin" && pwd == "123")
{
return new UserInfo() { UserName="admin",Pwd="",Age=50,Remark="我很帥" };
}
else
{
return null;
}
}

然後可以寫簡單的文件上傳下載

public class MyWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        /// <summary>
        /// 上傳文件
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [WebMethod]
        public bool FileUpload(byte[] bytes,string fileName)
        {
            try
            {
                //實例化內存對象MemoryStream,將byte數組裝入內存對象
                MemoryStream memory = new MemoryStream(bytes);
                //文件保存路徑
                string filePath = Server.MapPath("~/Files/" + fileName);
                //實例化文件對象
                FileStream fStream = new FileStream(filePath, FileMode.OpenOrCreate);
                //將內存對象寫入文件對象
                memory.WriteTo(fStream);
                //釋放對象
                memory.Close();
                memory.Dispose();
                fStream.Close();
                fStream.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        [WebMethod]
        public byte[] FileDownLoad(string FileName)
        {
            //加載路徑
            string filePath = Server.MapPath("~/Files/" + FileName);
            //實例化文件對象,並讀取指定的文件
            FileStream fs = File.OpenRead(filePath);
            int b1;
            //實例化內存對象
            System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
            //循環讀取文件並將文件轉換為byte[]
            while ((b1 = fs.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)b1));
            }
            return tempStream.ToArray();
        }

        [WebMethod]
        public List<FileManager> GetFileList()
        {
            //加載路徑
            string filePath = Server.MapPath("~/Files/");
            //實例化DirectoryInfo並加載指定路徑
            DirectoryInfo directory = new DirectoryInfo(filePath);
            List<FileManager> result = new List<FileManager>();

            //便利指定路徑下的所有文件夾
            foreach (DirectoryInfo item in directory.GetDirectories())
            {
                FileManager temp = new FileManager();
                temp.FileName = item.Name;
                temp.FilePath = item.FullName;
                temp.FileType = 1;
                result.Add(temp);
            }
            //遍歷指定路徑下的所有文件
            foreach (FileInfo item in directory.GetFiles())
            {
                FileManager temp2 = new FileManager();
                temp2.FileName = item.Name;
                temp2.FilePath = item.FullName;
                temp2.FileType = 2;
                result.Add(temp2);
            }
            return result;
        }
    }

在在MVC項目中的控制器中調用

public ActionResult FileUpload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file1)
        {
            Stream fileStream = file1.InputStream;
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            // 設置當前流的位置為流的開始
            fileStream.Seek(0, SeekOrigin.Begin);
            bool result = client.FileUpload(bytes, file1.FileName);
            if (result)
            {
                Response.Write("文件上傳成功!");
            }
            else
            {
                Response.Write("文件上傳失敗!");
            }
            return View();
        }

        public ActionResult FileDownLoad()
        {
            List<FileManager> result = client.GetFileList().ToList();
            StringBuilder sb = new StringBuilder();
            sb.Append("<ul>");
            foreach (var item in result)
            {
                    sb.Append(string.Format("<li><a href=‘/Home/FileDownLoad/{0}‘>{1}</a></li>", item.FilePath, item.FileName));
                    
            }
            sb.Append("</ul>");
            ViewBag.FileList = sb.ToString();
            return View();
        }

        [HttpPost]
        public ActionResult FileDownLoad(FormCollection coll)
        {
            string[] s = { "1", "3" };
            foreach (var item in s)
            {
                byte[] result = client.FileDownLoad(item);
                //輸出流的編碼
                Response.Charset = "UTF-8";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                //輸出類型為流文件
                Response.ContentType = "application/octet-stream";


                Response.AddHeader("Content-Disposition", "attachment; filename=" + "新建文本文檔.txt");
                Response.BinaryWrite(result);
                Response.Flush();
                Response.End();
                
            }
            return new EmptyResult();
        }

寫得不好,可能有錯請諒解,有錯請指出

.NET企業級應用WebService上傳下載文件