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:\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 附件服务的更多相关文章
- ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器
ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器一:闲谈一下:1.现在任务跟踪管理系统已经开发快要结束了,抽一点时间来写一下,想一想自己就有成就感啊!! ...
- (16)ASP.NET Core 通用主机(HostBuilder)
1.前言 ASP.NET Core应用程序可以配置和启动主机(Host).主机负责应用程序启动和生命周期管理.通用主机用于无法处理HTTP请求的应用程序.通用主机的用途是将HTTP管道从Web主机AP ...
- ASP.NET MVC传送参数至服务端
ASP.NET MVC传送参数至服务端,前端与服务端的写法,你可以参考与采用适合你的需求的.当你只传递一两个参数也许觉得没有什么,如果一个方法中带的参数多的话,可以考虑model,前端可以考虑对象进行 ...
- GPRS GPRS(General Packet Radio Service)是通用分组无线服务技术的简称,它是GSM移动电话用户可用的一种移动数据业务,属于第二代移动通信中的数据传输技术
GPRS 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . GPRS(General Packet Radio Service)是通用分组无线服务技术的简称,它是GSM移动电话用户可 ...
- MVC项目实践,在三层架构下实现SportsStore-09,ASP.NET MVC调用ASP.NET Web API的查询服务
ASP.NET Web API和WCF都体现了REST软件架构风格.在REST中,把一切数据视为资源,所以也是一种面向资源的架构风格.所有的资源都可以通过URI来唯一标识,通过对资源的HTTP操作(G ...
- ADs系列之通用数据解析服务GAS(即将开源)
面对成百上千的生产系统用户操作数据接入落地,你是否厌倦了每次机械编写打包解包的代码?对一次性接入多个数据的时候,还要对不同人联调,费时费力,你是否还会手忙脚乱,忙中不断出错?是否当数据出问题了,用的时 ...
- 在 ASP.NET Core 中执行租户服务
在 ASP.NET Core 中执行租户服务 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunna ...
- ASP.NET Core 2.0 : 五.服务是如何加载并运行的, Kestrel、配置与环境
"跨平台"后的ASP.Net Core是如何接收并处理请求的呢? 它的运行和处理机制和之前有什么不同? 本章从"宏观"到"微观"地看一下它的 ...
- ASP.NET WebAPI构建API接口服务实战演练
一.课程介绍 一.王小二和他领导的第一次故事 有一天王小二和往常一下去上早班,刚吃完早餐刚一打开电脑没一会儿.王小二的领导宋大宝走到他的面前,我们现在的系统需要提供服务给其他内部业务系统,我看你平时喜 ...
随机推荐
- 浅谈java中的祖先类Object
首先一道题: public class User{ private String name; private int age; public String getName() { return nam ...
- 【leetcode】492. Construct the Rectangle
problem 492. Construct the Rectangle 参考 1. Leetcode_492. Construct the Rectangle; 完
- Linux matlab.desktop文件
matlab建立菜单文件老是闪退,须用 matlab -desktop 完整配置 matlab.desktop [Desktop Entry] Name=MATLAB Exec=/usr/local/ ...
- 20155219付颖卓 《网络对抗技术》 Exp9 Web安全基础
实验后回答问题 1.SQL注入攻击原理,如何防御 ·SQL攻击的原理很简单,就是在用户名输入框里输入SQL语句,来欺骗数据库服务器进行恶意操作 ·防御可以从以下几个方面下手: (1)在web网页设计的 ...
- python 一些方法的时间测试
尝试一些方法的不同实现,比较一下时间,电脑比较渣,不过只是做个比较 虽然用python主要是方便,肯定是不快的,不过能快一点还是快一点好 numpy中大量使用同样 shape 的全 0 array,可 ...
- 【Jest】笔记二:Matchers匹配器
一.前言 什么是匹配器? 我们可以把匹配器看成,testng断言,这么理解就可以了 二.常用的匹配器 test('two plus two is four', () => { expect(2 ...
- http和https区别及概念
HTTP:是互联网上的应用广泛的一种网络协议,是一个客户端和服务器端请求和应答的传输协议,它可以使浏览器更加高效,使网络传输减少. HTTPS:是以安全为目标的HTTP通道,简单讲是HTTP的安全版, ...
- Python 安装beautifulsoup4遇到No module named setuptools问题解决方法
背景说明: 电脑win7-32 在Python 3.3.5下安装beautifulsoup4 4.6.0(下载链接https://pypi.org/project/beautifulsoup4/#fi ...
- 【java编程】java的关键字修饰符
一.transient java语言的关键字,变量修饰符,如果用transient声明一个实例变量,当对象存储时,它的值不需要维持.换句话来说就是,用transient关键字标记的成员变量不参与序列化 ...
- numpy用法
NumPy中创建特殊值 np.nan np.inf nan表示数据空缺 inf表示无穷 参考:https://www.cnblogs.com/haoxi/p/9175781.html