WebService上传文件到服务器(转)

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts; 
using System.IO;

/// <summary>
///FileHelper 的摘要说明
/// </summary>
public class FileHelper
{
    public static string TxtExtensions = "doc,docx,docm,dotx,dotm,txt,xml,rft,htm,html,mht,mhtml,wps,wtf";
    public static string XlsExtensions = "xls,xlsm,xlsb,xlsm,csv";
    public static string ImageExtensions = "jpg,jpeg,jpe,jfif,png,tif,tiff,gif,bmp,dib";
    public static string UpdateExtensions = "zip,rar";

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="fBitys"></param>
    /// <param name="fileName"></param>
    /// <param name="eMsg"></param>
    /// <returns></returns>
    public static bool SaveFile(byte[] fBitys, string fileName, ref string eMsg)
    {
        try
        {
            MemoryStream memoryStream = new MemoryStream(fBitys); //1.定义并实例化一个内存流,以存放提交上来的字节数组。
            FileStream fileUpload = new FileStream(fileName, FileMode.Create); ///2.定义实际文件对象,保存上载的文件。
            memoryStream.WriteTo(fileUpload); ///3.把内存流里的数据写入物理文件
            memoryStream.Close();
            fileUpload.Close();
            fileUpload = null;
            memoryStream = null;
            return true;
        }
        catch (Exception ex)
        {
            eMsg = ex.Message;
            return false;
        }
    }

    /// <summary>
    /// 文件类型
    /// </summary>
    public enum FileType
    {
        /// <summary>
        /// 文本文件
        /// </summary>
        Text,
        /// <summary>
        /// 图片文件
        /// </summary>
        Image,
        /// <summary>
        /// Excel文件
        /// </summary>
        Excel,
        /// <summary>
        /// 其他
        /// </summary>
        Other,
        UpdateFile
    }


    public static FileType GetFileType(string fileName)
    {
        string ext = Path.GetExtension(fileName);
        if (TxtExtensions.ToUpper().Contains(ext.ToUpper().Replace(".", "")) == true)
        {
            return FileType.Text;
        }
        else if (XlsExtensions.ToUpper().Contains(ext.ToUpper().Replace(".", "")) == true)
        {
            return FileType.Excel;
        }
        else if (ImageExtensions.ToUpper().Contains(ext.ToUpper().Replace(".", "")) == true)
        {
            return FileType.Image;
        }
        else if (UpdateExtensions.ToUpper().Contains(ext.ToUpper().Replace(".", "")) == true)
        {
            return FileType.UpdateFile;
        }
        else
        {
            return FileType.Other;
        }
    }

    public static System.Collections.Generic.Dictionary<FileType, string> filePathDic = new System.Collections.Generic.Dictionary<FileType, string>();
    public static string GetFilePath(FileType fType)
    {
        try
        {
            if (filePathDic.Keys.Contains(fType) == true)
            {
                return filePathDic[fType];
            }
            else
            {
                string filePath = "";
                switch (fType)
                {
                    case FileType.Excel:
                        filePath = ConfigurationSettings.AppSettings["ExcelFilePath"];
                        break;
                    case FileType.Image:
                        filePath = ConfigurationSettings.AppSettings["ImageFilePath"];
                        break;
                    case FileType.Other:
                        filePath = ConfigurationSettings.AppSettings["OtherFilePath"];
                        break;
                    case FileType.Text:
                        filePath = ConfigurationSettings.AppSettings["TextFilePath"];
                        break;
                    case FileType.UpdateFile:
                        filePath = ConfigurationSettings.AppSettings["UpdateFilePath"];
                        break;
                }
                if (string.IsNullOrEmpty(filePath))
                {
                    return "";
                }
                else
                {
                    filePathDic[fType] = filePath;
                    return filePath;
                }
            }
        }
        catch
        {
            return "";
        }
    }
}

定义WebService方法



[WebMethod]
    public string UploadFile(byte[] fBytes, string fileName, ref string eMsg)
    {
        try
        {
            FileHelper.FileType ft = FileHelper.GetFileType(fileName);
            string saveName = DateTime.Now.ToString("yyyyMMddHHmmssffffff") + ((int)((new Random()).NextDouble() * 1000000)).ToString() + Path.GetExtension(fileName);
            string savePath = "";
            switch (ft)
            {
                case FileHelper.FileType.Excel:
                    savePath = System.Configuration.ConfigurationManager.AppSettings["ExcelFilePath"] + "\\" + saveName;
                    break;
                case FileHelper.FileType.Image:
                    savePath = System.Configuration.ConfigurationManager.AppSettings["ImageFilePath"] + "\\" + saveName;
                    break;
                case FileHelper.FileType.Text:
                    savePath = System.Configuration.ConfigurationManager.AppSettings["TextFilePath"] + "\\" + saveName;
                    break;
                case FileHelper.FileType.UpdateFile:
                    savePath = System.Configuration.ConfigurationManager.AppSettings["UpdateFilePath"] + "\\" + fileName;
                    break;
                case FileHelper.FileType.Other:
                    savePath = System.Configuration.ConfigurationManager.AppSettings["OtherFilePath"] + "\\" + saveName;
                    break;
            }


            MemoryStream memoryStream = new MemoryStream(fBytes); //1.定义并实例化一个内存流,以存放提交上来的字节数组。
            FileStream fileUpload = new FileStream(savePath, FileMode.Create); ///2.定义实际文件对象,保存上载的文件。
            memoryStream.WriteTo(fileUpload); ///3.把内存流里的数据写入物理文件
            memoryStream.Close();
            fileUpload.Close();
            fileUpload = null;
            memoryStream = null;

            //获取IP地址
            System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            System.Net.IPAddress[] addrs = entry.AddressList;
            string ipAddress = "";
            if (addrs.Length > 0)
            {
                foreach (System.Net.IPAddress ipAddr in addrs)
                {
                    if (ipAddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipAddress = ipAddr.ToString();
                        break;
                    }
                }
                if (ipAddress == "")
                    ipAddress = addrs[0].ToString();
            }
            if (ft == FileHelper.FileType.UpdateFile)
            {
                return string.Format("http://{0}{1}/getUpdateFile.ashx?fn={2}", ipAddress, Server.HtmlEncode(HttpContext.Current.Request.ApplicationPath), fileName);
            }
            else
            {
                return string.Format("http://{0}{1}/ShowImage.ashx?fn={2}", ipAddress, Server.HtmlEncode(HttpContext.Current.Request.ApplicationPath), saveName);
            }
        }
        catch (Exception ex)
        {
            eMsg = ex.Message;
            return "";
        }
    }

以上方法返回一个服务器路径,其中ShowImage.ashx这个页面用于显示图片,getUpdateFile.ashx这个页面用于下载文件,代码如下:



public class ShowImage : IHttpHandler
{
    public static string FilePath = FileHelper.GetFilePath(FileHelper.FileType.Image);
    public void ProcessRequest(HttpContext context)
    {
        string fileName = context.Request.QueryString["fn"];

        fileName = FilePath + "\\" + fileName;
        context.Response.ContentType = "image/JPEG";
        try
        {
            context.Response.WriteFile(fileName);
            context.Response.Flush();
        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}



public class getUpdateFile : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string fileName = context.Request.QueryString["fn"];

        context.Response.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        try
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                string filePath = FileHelper.GetFilePath(FileHelper.FileType.UpdateFile) + "\\" + fileName;//路径

                //以字符流的形式下载文件
                byte[] bytes = null;
                using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
                {
                    bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                }
                context.Response.BinaryWrite(bytes);

            }
        }
        catch
        {
        }
        context.Response.Flush();
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

客户端代码



 public static string UpLoadFile(string fileName, ref string eMsg)
        {
           //wms:WebService
            if (wms == null)
            {
                wms = new Service();
            }
            byte[] fByte;
            
            fByte = File.ReadAllBytes(fileName);

            return wms.UploadFile(fByte, fileName, ref eMsg);
        }

转载:http://www.360doc.com/content/13/1202/09/14880949_333799494.shtml

posted @ 2013-12-03 09:44  gin飞飞ing  阅读(475)  评论(0编辑  收藏  举报