[toc]
總述:
用了好久的附件分離服務, .NET 2.0平臺開始使用. 配置好服務後, 由調用端定義並管理目錄級次. 調用端存儲目錄便可.
附件服務: web
相應配置節點放入 web.config app
<?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[] { }; } } } }
以下以簽名爲例, 表示的調用代碼; ui
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)));
同理, 相應的上傳配置文件, 須要自定義目錄, 下載時取得端口, 須要自定義配置:this
<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" />