[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:\XXX\FileAttachments\"/>
<add key="pathSignature" value="D:\XXX\Signature\"/>
</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 + "\r\n");
}
}
}) { 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 + "\r\n");
}
}
}) { 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("\r\n--" + boundary + "\r\n");
var endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //请求头部信息
var headerBuilder = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", 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="XXX\Content\Signatures\" />
<add key="ProjectAttachmentPath" value="XXX/Content/ProjectAttachmentFiles/" />
<add key="FileServer" value="/XXXFiles" />

Asp.NET 简易通用WebServices 附件服务的更多相关文章

  1. ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器

    ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器一:闲谈一下:1.现在任务跟踪管理系统已经开发快要结束了,抽一点时间来写一下,想一想自己就有成就感啊!!  ...

  2. (16)ASP.NET Core 通用主机(HostBuilder)

    1.前言 ASP.NET Core应用程序可以配置和启动主机(Host).主机负责应用程序启动和生命周期管理.通用主机用于无法处理HTTP请求的应用程序.通用主机的用途是将HTTP管道从Web主机AP ...

  3. ASP.NET MVC传送参数至服务端

    ASP.NET MVC传送参数至服务端,前端与服务端的写法,你可以参考与采用适合你的需求的.当你只传递一两个参数也许觉得没有什么,如果一个方法中带的参数多的话,可以考虑model,前端可以考虑对象进行 ...

  4. GPRS GPRS(General Packet Radio Service)是通用分组无线服务技术的简称,它是GSM移动电话用户可用的一种移动数据业务,属于第二代移动通信中的数据传输技术

    GPRS 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . GPRS(General Packet Radio Service)是通用分组无线服务技术的简称,它是GSM移动电话用户可 ...

  5. MVC项目实践,在三层架构下实现SportsStore-09,ASP.NET MVC调用ASP.NET Web API的查询服务

    ASP.NET Web API和WCF都体现了REST软件架构风格.在REST中,把一切数据视为资源,所以也是一种面向资源的架构风格.所有的资源都可以通过URI来唯一标识,通过对资源的HTTP操作(G ...

  6. ADs系列之通用数据解析服务GAS(即将开源)

    面对成百上千的生产系统用户操作数据接入落地,你是否厌倦了每次机械编写打包解包的代码?对一次性接入多个数据的时候,还要对不同人联调,费时费力,你是否还会手忙脚乱,忙中不断出错?是否当数据出问题了,用的时 ...

  7. 在 ASP.NET Core 中执行租户服务

    在 ASP.NET Core 中执行租户服务 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunna ...

  8. ASP.NET Core 2.0 : 五.服务是如何加载并运行的, Kestrel、配置与环境

    "跨平台"后的ASP.Net Core是如何接收并处理请求的呢? 它的运行和处理机制和之前有什么不同? 本章从"宏观"到"微观"地看一下它的 ...

  9. ASP.NET WebAPI构建API接口服务实战演练

    一.课程介绍 一.王小二和他领导的第一次故事 有一天王小二和往常一下去上早班,刚吃完早餐刚一打开电脑没一会儿.王小二的领导宋大宝走到他的面前,我们现在的系统需要提供服务给其他内部业务系统,我看你平时喜 ...

随机推荐

  1. 打印sql

    $query=$sql->where([ 'test_id'=>24, 'name'=>'小洋' ]); //打印sql; $query->prepare(Yii::$app- ...

  2. excel 格式化姓名

                在做excel时,难免会遇到输入姓名对齐这种情况,如果数据少时我们可以手动敲空格来进行对齐,但数据量大时,手动调整就不是好办法了.     此时我们可以通过excel自带公式对 ...

  3. ValueError: attempted relative import beyond top-level package

    python 项目 在pycharm中, 在某个文件夹下: 右键--> mark directory as --> source root 如何在python脚本或者shell中 用代码实 ...

  4. CSS学习笔记_day3

    一.浮动的清除 1.给祖先元素加高度 <style> * { padding: 0; margin: 0; } .box1 { height: 100px; /**/ } ul { /*去 ...

  5. java语言基础--方法的执行图解

    1.调用m1方法(压栈) 2.m1调用m2方法(压栈) 3.m2调用m3方法(压栈) 4.运行m3(弹栈) 5.运行m2(弹栈) 6.运行m1(弹栈)

  6. cf——C. Serval and Parenthesis Sequence

    括号正确匹配问题,应该不难 #include <iostream> #include <cstring> #include <string> #include &l ...

  7. 对C语言指针的理解

    一个小程序引发对于C语言指针的思考: #include <bits/stdc++.h> using namespace std; void my_swap (int* a,int* b) ...

  8. cms建站

    1. 搭建php环境 phpnow软件安装(下载地址:  http://www.phpnow.org) 注意如果安装失败,请用以下解决办法: 1.请使用命令提示符(管理员)2.打开后进入PHPnow目 ...

  9. git 提交本地工程

    1> 进入github 建立repository 2> 得到git master 地址 3> 得到进入本地工程目录 右键->git bash here 4>执行 以下命令 ...

  10. 20165313 《网络对抗技术》 Kali安装

    一.目的要求 下载 安装 网络 共享 软件源 二.主要步骤 我主要是按照最新超详细虚拟机VMware安装Kali Linux 这个方法做的就没有步骤描述了. 安装结果图: 注意事项 安装过程中如果没有 ...