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接口服务实战演练
一.课程介绍 一.王小二和他领导的第一次故事 有一天王小二和往常一下去上早班,刚吃完早餐刚一打开电脑没一会儿.王小二的领导宋大宝走到他的面前,我们现在的系统需要提供服务给其他内部业务系统,我看你平时喜 ...
随机推荐
- MySQL 相关记录
删除courseID_tr之前: 新建之后: show create trigger: 下面是mysql-5.7.21-win64解压目录下的my.ini文件中的内容 [client] default ...
- Spring框架:@ResponseBody 中文乱码----------我的主题站内单点登录
问题背景 本文并不是介绍@ResponseBody注解,也不是中文乱码问题的大汇总笔记,这些网上都有很多内容了.这边仅对几年前,一个卡壳了挺久时间的问题的解决过程做一个记录,以警惕自己,达到自醒得目的 ...
- Linux 文件恢复
可以恢复,使用系统自还工具debugfs来还原删除的文件 步骤详解 1. 查看一下当前系统版本号,及文件系统格式 [root@localhost ~]# df -T Filesystem Type 1 ...
- 如何在运行时(Runtime)获得泛型的真正类型
前言 由于Java 的类型擦除机制,在编译时泛型都被转为了Object,例如List<String>经过编译之后将变为类型 List.可以通过以下的方式再运行时获得泛型的真正类型 泛型如何 ...
- 20164322 韩玉婷-----Exp5 MSF基础应
Exp5 MSF基础应用 1.基础问题回答 exploit: 是指攻击者或渗透测试者利用一个系统.应用或服务中的安全漏洞所进行的攻击行为, 包括利用缓冲区溢出.Web应用程序漏洞攻击,以及利用配置错误 ...
- Apache Commons 工具类简单使用
Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.下面是我这几年做开发过程中自己用过的工具类做简单介绍. 组件 功能介绍 BeanUtils 提供了对于 ...
- 653. Two Sum IV - Input is a BST-easy
我不懂有没有收藏之类的功能,收藏别人的解法. tql,不懂为什么直接比较set里的值,不是两个数sum么 有一些答案都用到了iterator迭代器 http://www.cplusplus.com/r ...
- PTA8
这个作业属于哪个课程 C语言程序设计2 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/software-engineering-class2-2018/ ...
- Go语言极速入门手册.go
Github: https://github.com/coderzh/CodeTips /* gotips_test.go: Golang速学速查速用代码手册 Source: github.com/c ...
- C++函数装饰器
今天在网上看到一个python实现的函数装饰器,尝试用C++11实现了一下,最后很粗糙的完成了,代码如下. 函数装饰器:接受一个函数.将此函数进行一些装饰,成为另一个函数.新生产的函数具有原函数的功能 ...