Asp.NET 简易通用WebServices 附件服务

[toc]
总述:
用了很久的附件分离服务, .NET 2.0平台开始使用.  配置好服务后, 由调用端定义并管理目录级次.  调用端存储目录即可. 
附件服务: 

相应配置节点放入 web.config 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <httpRuntime maxRequestLength="409600" executionTimeout="60000" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/>
    <compilation debug="true"/>
  </system.web>
  <appSettings>
    <add key="path" value="D:XXXFileAttachments"/>
    <add key="pathSignature" value="D:XXXSignature"/>
  </appSettings>
</configuration>

代码部分; 
- 采用较早的.NET 2.0 部分, 所以写法较旧, 写入时委托异步先写临时文件, 完毕再写入真实文件. 减少一定的资源占用. 

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.Services;
using System.IO;
using System.Configuration;
using System.Text;
using System.Threading;

namespace SY_FileService
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class FileService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public bool upload(byte[] f, string path,string fileName)
        {
            try
            {
                var path1 = ConfigurationManager.AppSettings["path"] + path;

                if (!Directory.Exists(Path.GetDirectoryName(path1)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path1));
                }

                if (!File.Exists(path1))
                {
                    new Thread(delegate()
                    {
                        var tmppath = ConfigurationManager.AppSettings["path"] +"文件映射/"+ DateTime.Now.ToString("yyyyMMdd") + ".txt";
                        if (!Directory.Exists(Path.GetDirectoryName(tmppath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(tmppath));
                        }
                        using (FileStream fs = new FileStream(tmppath, FileMode.Append, FileAccess.Write, FileShare.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                            {
                                sw.Write(path + " * " + fileName + "
");
                            }
                        }
                    }) {  IsBackground=true}.Start();
                   

                    File.Create(path1).Close();
                }
                File.WriteAllBytes(path1, f);
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        } 

        [WebMethod]
        public bool Delete(string path)
        {
            try
            {
                var path1 = ConfigurationManager.AppSettings["path"] + path;

                if (!Directory.Exists(Path.GetDirectoryName(path1)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path1));
                }

                if (File.Exists(path1))
                {
                    File.Delete(path1);
                }
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }
        [WebMethod]
        public byte[] Download(string path)
        {
            try
            {
                var path1 = ConfigurationManager.AppSettings["path"] + path;

                if (!Directory.Exists(Path.GetDirectoryName(path1)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path1));
                }

                if (File.Exists(path1))
                {
                    return File.ReadAllBytes(path1);
                }
                return new byte[] { };
            }
            catch (Exception)
            {
                return new byte[] { };
            }
        }

        [WebMethod]
        public bool uploadSignature(byte[] f, string path, string fileName)
        {
            try
            {
                var path1 = ConfigurationManager.AppSettings["pathSignature"] + path;

                if (!Directory.Exists(Path.GetDirectoryName(path1)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path1));
                }

                if (!File.Exists(path1))
                {
                    new Thread(delegate()
                    {
                        var tmppath = ConfigurationManager.AppSettings["path"] + "文件映射/" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                        if (!Directory.Exists(Path.GetDirectoryName(tmppath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(tmppath));
                        }
                        using (FileStream fs = new FileStream(tmppath, FileMode.Append, FileAccess.Write, FileShare.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                            {
                                sw.Write(path + " * " + fileName + "
");
                            }
                        }
                    }) { IsBackground = true }.Start();


                    File.Create(path1).Close();
                }
                File.WriteAllBytes(path1, f);
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }
        [WebMethod]
        public byte[] DownloadSignature(string path)
        {
            try
            {
                var path1 = ConfigurationManager.AppSettings["pathSignature"] + path;

                if (!Directory.Exists(Path.GetDirectoryName(path1)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path1));
                }

                if (File.Exists(path1))
                {
                    return File.ReadAllBytes(path1);
                }
                return new byte[] { };
            }
            catch (Exception ex)
            {
                
                return new byte[] { };
            }
        }
    }
}

如下以签名为例, 表示的调用代码; 

        HttpResult HttpUploadFile(string url, byte[] fileBuffer, string fileName)
        {
            // 设置参数
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = new CookieContainer();
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            var itemBoundaryBytes = Encoding.UTF8.GetBytes("
--" + boundary + "
");
            var endBoundaryBytes = Encoding.UTF8.GetBytes("
--" + boundary + "--
");

            //请求头部信息 
            var headerBuilder = new StringBuilder(string.Format("Content-Disposition:form-data;name="file";filename="{0}"
Content-Type:application/octet-stream

", fileName));
            var headerBytes = Encoding.UTF8.GetBytes(headerBuilder.ToString());

            var requestStream = request.GetRequestStream();
            requestStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            requestStream.Write(headerBytes, 0, headerBytes.Length);
            requestStream.Write(fileBuffer, 0, fileBuffer.Length);
            requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            requestStream.Close();

            //发送请求并获取相应回应数据
            var response = request.GetResponse() as HttpWebResponse;

            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            var responseStream = response.GetResponseStream();
            var streamReader = new StreamReader(responseStream, Encoding.UTF8);

            //返回结果
            string content = streamReader.ReadToEnd();
            var result = JsonConvert.DeserializeObject<HttpResult>(content);
            return result;
        }


     public byte[] DownloadSignature(string path) {
            BMPFileService.DownloadSignatureRequest inValue = new BMPFileService.DownloadSignatureRequest();
            inValue.Body = new BMPFileService.DownloadSignatureRequestBody();
            inValue.Body.path = path;
            BMPFileService.DownloadSignatureResponse retVal = ((BMPFileService.FileServiceSoap)(this)).DownloadSignature(inValue);
            return retVal.Body.DownloadSignatureResult;
        }

//使用调用:
appr.Signature = a["签名"] == DBNull.Value ? "" : Convert.ToBase64String(fs.DownloadSignature(HttpUtility.UrlDecode(a["签名"].ToString(), Encoding.UTF8)));

同理, 相应的上传配置文件, 需要自定义目录, 下载时取得端口, 需要自定义配置:

    <add key="FileApiHost" value="localhost:9992" />    
    <add key="SignPath" value="XXXContentSignatures" />
    <add key="ProjectAttachmentPath" value="XXX/Content/ProjectAttachmentFiles/" />
    <add key="FileServer" value="/XXXFiles" />
原文地址:https://www.cnblogs.com/hijushen/p/10551293.html