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接口服务实战演练
一.课程介绍 一.王小二和他领导的第一次故事 有一天王小二和往常一下去上早班,刚吃完早餐刚一打开电脑没一会儿.王小二的领导宋大宝走到他的面前,我们现在的系统需要提供服务给其他内部业务系统,我看你平时喜 ...
随机推荐
- Day01_Python学习今日收获
1.关键字 break:终止本层循环,即如果是双层嵌套循环,那么就终结最内层循环 注意:如果在for或while循环中终止,他们任何对应的else语句块也将不执行. 2.关键字continue:跳过当 ...
- IDEA 编译时 报 “常量字符串过长” 解决办法
从eclipse 工具转到 IDEA 工具的时候,出现了一些问题,在这里记录一下,以便之后使用到,废话不多说. 在编译项目时,出现错误为:"常量字符串过长" ,我当时想这个问题需要 ...
- EfRepository
using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using ...
- mpvue开发小程序记录
1.同一组件内嵌套的 v-for 不能连续使用相同的索引,目前为: index,index <li v-for="(list, index) in datas" :key=& ...
- js中Array数组的属性和方法
这是我自己整理出来的一些关于Array数组的属性和方法,即查即用. 1.Array.length属性:数组的项数组,始终返回0或者更大的值. 2.instanceof操作符:value instanc ...
- sql base and plsql and database
sql base: http://www.runoob.com/sql/sql-tutorial.html Oracle系统表整理+常用SQL语句收集: https://www.cnblogs.co ...
- 653. Two Sum IV - Input is a BST-easy
我不懂有没有收藏之类的功能,收藏别人的解法. tql,不懂为什么直接比较set里的值,不是两个数sum么 有一些答案都用到了iterator迭代器 http://www.cplusplus.com/r ...
- QC3.0充电标准
- Java字符串与数组
字符串查找 indexOf(String s)方法返回搜索的字符或字符串首次出现的位置 lastIndexOf(String s)方法返回搜索的字符或字符串最后一次出现的位置 获取索引位置的字符 ch ...
- pychrom 快捷键
1.pycharm使多行代码同时缩进 鼠标选中多行代码后,按下Tab键,一次缩进四个字符 2.pycharm使多行代码同时左移 鼠标选中多行代码后,同时按住shift+Tab键,一次左移四个字符 1. ...