/** * 上传文件 */ protected string uploadFiles(Object upauth, ArrayList filelist, ProgressDelegate progress = null) { string upresults = "["; Dictionary <Object, Object> dt = (Dictionary <Object, Object>)upauth; object nsp_host, nsp_tstr, secret, nsp_tapp; if (dt.TryGetValue((object)"nsp_host", out nsp_host) == false || dt.TryGetValue((object)"nsp_tstr", out nsp_tstr) == false || dt.TryGetValue((object)"secret", out secret) == false || dt.TryGetValue((object)"nsp_tapp", out nsp_tapp) == false) { throw new Exception("上传鉴权出错"); } foreach (Object filename in filelist) { string uploadresult = null; string mksinglefile = null; try { uploadresult = uploadFile(nsp_tapp.ToString(), secret.ToString(), nsp_host.ToString(), nsp_tstr.ToString(), filename.ToString(), progress); mksinglefile = mkfilestr(uploadresult); } catch (Exception err) { NSPLog.log(LogMsgType.NSP_LOG_ERR, err.Message); throw err; } upresults += mksinglefile + ","; } upresults = upresults.Substring(0, upresults.Length - 1) + "]"; return(upresults); }
public Object callService(string svrname, Object reqs) { NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "调用平台服务 " + svrname); //记录系统级post数据 SortedDictionary <string, string> dt = new SortedDictionary <string, string>(); if (this.isSysLevel) { dt.Add(NSP_APP, this.id); } else { dt.Add(NSP_SID, this.id); } try { if (reqs == null) { Dictionary <Object, Object> empty = new Dictionary <object, object>(); reqs = empty; } string serires = seri.Serialize(reqs); dt.Add(NSP_PARAMS, serires); dt.Add(NSP_SVC, svrname); DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); DateTime nowTime = DateTime.Now; long unixTime = (long)Math.Round((nowTime - startTime).TotalSeconds, MidpointRounding.AwayFromZero); if (ts_adjustment != 0) { dt.Add(NSP_TS, (unixTime + ts_adjustment).ToString()); } else { dt.Add(NSP_TS, unixTime.ToString()); } dt.Add(NSP_FMT, "php-rpc"); //模拟post并获取结果 string data = getPostData(this.secret, dt); NSPResponse response = request(NSP_URL, data); if (response.nsp_code == 109) { NSPLog.log(LogMsgType.NSP_LOG_ERR, "客户端系统时间有误"); ts_adjustment = (long)(DateTime.Parse(response.server_time) - nowTime).TotalSeconds; dt[NSP_TS] = (unixTime + ts_adjustment).ToString(); data = getPostData(this.secret, dt); response = request(NSP_URL, data); } return(seri.Deserialize(response.content)); } catch (Exception err) { NSPLog.log(LogMsgType.NSP_LOG_ERR, "调用服务 " + svrname + " 返回信息解析错误," + err.ToString()); throw err; } }
/** * 下载文件 */ protected bool downloadfile(string url, string savefullpath, ProgressDelegate progress = null) { //处理下载url不符合rfc规范的情况 MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); if (getSyntax != null && flagsField != null) { foreach (string scheme in new[] { "http", "https" }) { UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme }); if (parser != null) { int flagsValue = (int)flagsField.GetValue(parser); // Clear the CanonicalizeAsFilePath attribute if ((flagsValue & 0x1000000) != 0) { flagsField.SetValue(parser, flagsValue & ~0x1000000); } } } } NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "请求下载 " + url); //文件下载 WebRequest req = WebRequest.Create(url); WebResponse pos = req.GetResponse(); long totalbytes = pos.ContentLength; Stream s = pos.GetResponseStream(); FileStream fs = new FileStream(savefullpath, FileMode.OpenOrCreate, FileAccess.Write); byte[] buffer = new byte[1024]; int bytesRead = s.Read(buffer, 0, buffer.Length); long donebytes = 0; while (bytesRead > 0) { fs.Write(buffer, 0, bytesRead); bytesRead = s.Read(buffer, 0, buffer.Length); if (progress != null) { donebytes += bytesRead; progress(donebytes, totalbytes); } } fs.Close(); s.Close(); pos.Close(); return(true); }
// //暂时提供 VFS 和 user两个操作对象 // public T service <T>(Type item) { if (item.Equals(typeof(VFS))) { VFS v = new VFS(this); return((T)(object)v); } else if (item.Equals(typeof(USER))) { USER u = new USER(this); return((T)(object)u); } NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "调用服务对象 " + item.Name); return(default(T)); }
protected NSPResponse request(string httpurl, string data) { NSPResponse response = new NSPResponse(); NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "请求url " + httpurl + "?" + data); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(httpurl + "?" + data); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add("Accept-Encoding", "gzip"); string strResult; HttpWebResponse res = (HttpWebResponse)req.GetResponse(); Stream smRes = res.GetResponseStream(); { strResult = res.ContentEncoding; if (strResult == "gzip") { smRes = new GZipStream(smRes, CompressionMode.Decompress); } StreamReader sr = new StreamReader(smRes, System.Text.Encoding.UTF8); strResult = sr.ReadToEnd(); sr.Close(); } if (res != null) { res.Close(); } if (smRes != null) { smRes.Close(); } response.status_code = Convert.ToInt32(res.StatusCode); response.nsp_code = Convert.ToInt32(res.Headers["NSP_STATUS"]); response.server_time = res.Headers["Date"]; response.content = strResult; NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "请求url返回 " + strResult); return(response); }
public static void turnOnLog(bool choice) { whetherlog = choice; if (whetherlog == false) { return; } IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName); if (oIPHost.AddressList.Length > 0) { string ipinfo = string.Empty; foreach (IPAddress ipa in oIPHost.AddressList) { ipinfo += ipa.ToString() + " "; } NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "开始记录日志: " + ipinfo); } }
public Result uploadFileProgress(string dirpath, string file, ProgressDelegate progress) { NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "调用上传服务回调函数接口 uploadFileProgress"); // call upauth 上传鉴权 Object upauth = this.callService("nsp.vfs.upauth", null); ArrayList filesArray = new ArrayList(); filesArray.Add(file); // upload 上传 string upfiles = uploadFiles(upauth, filesArray, progress); // call mkfile 创建上传文件 Dictionary <Object, Object> dt = new Dictionary <object, object>(); dt["files"] = upfiles; dt["path"] = dirpath; Object res = this.callService("nsp.vfs.mkfile", dt); return((Result)NSPWrapper.toBean(res, typeof(Result))); }
public bool downloadFile(string objfile, string savefullname, ProgressDelegate progress = null) { NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "下载文件 " + objfile); //获取文件url Dictionary <Object, Object> sendParams = new Dictionary <object, object>(); Dictionary <Object, Object> files = new Dictionary <object, object>(); Dictionary <Object, Object> fields = new Dictionary <object, object>(); files.Add(0, objfile); fields.Add(0, "url"); sendParams.Add(0, files); sendParams.Add(1, fields); Result res = (Result)NSPWrapper.toBean(this.callService("nsp.VFS.getattr", sendParams), typeof(Result)); if (res == null || res.successList.Count() == 0) { return(false); } string url = res.successList[0].url; return(downloadfile(url, savefullname, progress)); }
/** * 上传单个文件 */ protected string uploadFile(string appid, string secret, string host, string tstr, string filepath, ProgressDelegate progress = null) { NSPLog.log(LogMsgType.NSP_LOG_NOTICE, "上传文件 " + filepath); SortedDictionary <string, string> dt = new SortedDictionary <string, string>(); dt.Add(NSP_APP, appid); dt.Add(NSP_FMT, "JSON"); DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); DateTime nowTime = DateTime.Now; long unixTime = (long)Math.Round((nowTime - startTime).TotalSeconds, MidpointRounding.AwayFromZero); dt.Add(NSP_TS, unixTime.ToString()); dt.Add(NSP_TSTR, tstr); string keyres = getNSPKey(secret, dt); dt.Add(NSP_KEY, keyres); string url = "http://" + host + "/upload/up.php?"; Uri uri = new Uri(url); string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); //请求 WebRequest req = WebRequest.Create(uri); req.Method = "POST"; req.ContentType = "multipart/form-data; boundary=" + boundary; //组织表单数据 StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <string, string> kv in dt) { string k = kv.Key.ToString(); string v = kv.Value.ToString(); sb.Append("--" + boundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\"" + k + "\""); sb.Append("\r\n\r\n"); sb.Append(v); sb.Append("\r\n"); } string filename = Path.GetFileName(filepath); sb.Append("--" + boundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\"" + filename + "\"; filename=\"" + filepath + "\""); sb.Append("\r\n"); sb.Append("Content-Type: text/plain"); sb.Append("\r\n\r\n"); string head = sb.ToString(); byte[] form_data = Encoding.UTF8.GetBytes(head); //结尾 byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //文件 FileStream fileStream; try { fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read); } catch (Exception) { NSPLog.log(LogMsgType.NSP_LOG_ERR, "无法打开文件 " + filepath); throw new Exception("无法打开指定上传文件: " + filepath); } //post总长度 long length = form_data.Length + fileStream.Length + foot_data.Length; req.ContentLength = length; Stream requestStream = req.GetRequestStream(); //发送表单参数 requestStream.Write(form_data, 0, form_data.Length); byte[] buffer = new Byte[checked ((uint)Math.Min(4096, (int)fileStream.Length))]; int bytesRead = 0; long donebytes = 0; long totalbytes = fileStream.Length; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); if (progress != null) { donebytes += bytesRead; progress(donebytes, totalbytes); } } requestStream.Write(foot_data, 0, foot_data.Length); requestStream.Close(); WebResponse pos = null; try { pos = req.GetResponse(); } catch (WebException err) { NSPLog.log(LogMsgType.NSP_LOG_ERR, "文件 " + filepath + " 上传出错"); NSPLog.log(LogMsgType.NSP_LOG_ERR, err.Message); throw new Exception("文件传输错误: " + filepath); } StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8); string html = sr.ReadToEnd().Trim(); sr.Close(); if (pos != null) { pos.Close(); pos = null; } if (req != null) { req = null; } return(html); }