You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

850 lines
36 KiB

using Container.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
//using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Container.Control;
using Container.Model;
namespace Container.Services
{
class HttpClient
{
public string message;
public string url;
//public string httpStr;
private Class_Log log = new Class_Log();
App app = ((App)Application.Current);
public string HttpPost()//string postDataStr, string tradecode, string devicecode, string id, string organcode,string producttype
{
try
{
message = message.Replace("'", "\"");
return GetWebService(message); //"jsonparam=" + message.Length.ToString().PadLeft(8, '0') +
}
catch (Exception ex)
{
log.WriteLogFile("错误信息:" + ex.ToString(), "HttpClient");
return "";
}
}
/// <summary>
///
/// </summary>
/// <param name="url">地址</param>
/// <param name="method">方法</param>
/// <param name="param">json参数</param>
/// <returns></returns>
public string WebServiceApp(string param)
{
//转换输入参数的编码类型,获取bytep[]数组
byte[] byteArray = Encoding.UTF8.GetBytes(param);
//初始化新的webRequst
//1. 创建httpWebRequest对象
if (message != "")
url = url + "?" + message;
//url = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(url));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
log.WriteLogFile("SendUrl:" + url, "HttpClient");
log.WriteLogFile("SendMessage:" + param, "HttpClient");
//2. 初始化HttpWebRequest对象
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
//webRequest.ProtocolVersion =
webRequest.ContentLength = byteArray.Length;
//3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
//4. 读取服务器的返回信息
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
php.Close();
response.Close();
log.WriteLogFile("RecvMessage:" + phpend, "HttpClient");
return phpend;
}
/// <summary>
/// Http post方法
/// </summary>
/// <param name="param">json参数</param>
/// <param name="url">服务器地址</param>
/// <returns></returns>
public string PostMoths(string param, string url)
{
log.WriteLogFile("Sendurl:" + url, "HttpClient");
log.WriteLogFile("SendMessage:" + param, "HttpClient");
string strURL = url;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
string paraUrlCoded = param;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
log.WriteLogFile("RecvMessage:" + strValue, "HttpClient");
return strValue;
}
/// <summary>
///
/// </summary>
/// <param name="url">地址</param>
/// <param name="method">方法</param>
/// <param name="param">json参数</param>
/// <returns></returns>
public string GetWebService(string param)
{
//message = message.Replace("'", "\"");
string postDataStr = param;
if (!param.Trim().Equals(""))
url += "?" + param;
log.WriteLogFile("SendUrl:" + url, "HttpClient");
CookieContainer cookie = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 59000;
//request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = cookie.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
log.WriteLogFile("RecvMessage:" + retString, "HttpClient");
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
public static void DelectDir(string srcPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
File.Delete(i.FullName); //删除指定文件
}
}
}
catch (Exception e)
{
throw;
}
}
/// <summary>
/// 下载离线数据
/// </summary>
/// <param name="path">文件下载地址</param>
/// <param name="filename">应用程序文件名(不带扩展名)</param>
/// <returns>下载成功标志</returns>
public bool DownLoadFiles(string path,ref string filename)
{
try
{
var httpPath = path.Substring(0, path.IndexOf("://") + 3);
var fileBackPath = path.Substring(path.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/");
path = httpPath+ fileBackPath;
string localFile = string.Empty;//本地压缩文件保存的路径
string Unzippath = string.Empty;//解压文件所在的路径
path = path.Replace(@"\", "/");
if (path.Contains("/"))
{
var filename1 = path.Substring(path.LastIndexOf("/") + 1, path.LastIndexOf(".zip") - path.LastIndexOf("/") - 1);
localFile = AppDomain.CurrentDomain.BaseDirectory + "/zipfile" + path.Substring(path.LastIndexOf("/"));//本地地址
Unzippath = AppDomain.CurrentDomain.BaseDirectory + "/exefile/exefile" + "/" + filename1;//本地地址
}
else
{
var filename1 = path.Substring(0, path.LastIndexOf(".zip"));
localFile = AppDomain.CurrentDomain.BaseDirectory + "/zipfile" + path;
Unzippath = AppDomain.CurrentDomain.BaseDirectory + "/exefile/exefile" + "/" + filename1;
}
//判断压缩包是否存在、
if (File.Exists(localFile))
{
File.Delete(localFile);
}
if (Directory.Exists(Unzippath))
{
DelectDir(Unzippath);
}
if (File.Exists(localFile + ".temp"))
{
File.Delete(localFile + ".temp");
}
//下载应用程序压缩文件
if (!File.Exists(localFile + ".temp"))
{
try
{
using (Stream fileStream = new FileStream(localFile + ".temp", FileMode.OpenOrCreate))
{
fileStream.Seek(fileStream.Length, SeekOrigin.Current);
log.WriteLogFile(path, "HttpClient");//服务器地址
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
request.AddRange(fileStream.Length);
//下载文件
HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
using (Stream netStream = respone.GetResponseStream())
{
long totalDownloadedByte = 0;
byte[] read = new byte[1024];
int realReadLen = netStream.Read(read, 0, read.Length);
while (realReadLen > 0)
{
totalDownloadedByte = realReadLen + totalDownloadedByte;
fileStream.Write(read, 0, realReadLen);
realReadLen = netStream.Read(read, 0, read.Length);
System.Windows.Forms.Application.DoEvents();
}
netStream.Close();
}
fileStream.Close();
}
//删除temp文件
if (File.Exists(localFile))
{
File.Delete(localFile);
}
File.Move(localFile + ".temp", localFile);
//解压文件
ZipFloClass.UnZip(localFile, Unzippath);
filename = Unzippath;
//app.Appdowninfo.exepath = Unzippath+ "/" + filename;
}
catch (Exception ex)
{
//File.Move(localFile + ".temp", localFile);
log.WriteLogFile(ex.ToString(), "HttpClient");
return false;
}
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
return false;
}
return true;
}
/// <summary>
/// 下载图片
/// </summary>
/// <param name="path">文件下载地址</param>
/// <param name="filename">应用程序文件名(不带扩展名)</param>
/// <returns>下载成功标志</returns>
public bool DownLoadIcon( ref string filepath)
{
try
{
var httpPath = filepath.Substring(0, filepath.IndexOf("://") + 3);
var fileBackPath = filepath.Substring(filepath.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/");
filepath = httpPath + fileBackPath;
string Iconpath = string.Empty;//文件保存的路径
var path = filepath;
if (path.Contains("/"))
{
var fileList = path.Split('/');
var fileType=path.Substring(path.LastIndexOf(".") , path.Length - path.LastIndexOf("."));
path = fileList[fileList.Length-2]+ fileType;
}
//else
//{
// path = path;
//}
Iconpath = AppDomain.CurrentDomain.BaseDirectory + @"AppIcon\" + path;
log.WriteLogFile("图标地址" + Iconpath, "Icon");
if (File.Exists(Iconpath))
{
filepath = Iconpath;
return true;
}
if (File.Exists(Iconpath + ".temp"))
{
File.Delete(Iconpath + ".temp");
}
//下载应用程序压缩文件
if (!File.Exists(Iconpath + ".temp"))
{
try
{
using (Stream fileStream = new FileStream(Iconpath + ".temp", FileMode.OpenOrCreate))
{
fileStream.Seek(fileStream.Length, SeekOrigin.Current);
log.WriteLogFile(filepath, "HttpClient");//服务器地址
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);
request.AddRange(fileStream.Length);
//下载文件
HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
using (Stream netStream = respone.GetResponseStream())
{
long totalDownloadedByte = 0;
byte[] read = new byte[1024];
int realReadLen = netStream.Read(read, 0, read.Length);
while (realReadLen > 0)
{
totalDownloadedByte = realReadLen + totalDownloadedByte;
fileStream.Write(read, 0, realReadLen);
realReadLen = netStream.Read(read, 0, read.Length);
System.Windows.Forms.Application.DoEvents();
}
netStream.Close();
}
fileStream.Close();
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
//File.delete(Iconpath + ".temp", Iconpath);
return false;
}
//删除temp文件
if (File.Exists(Iconpath))
{
File.Delete(Iconpath);
}
File.Move(Iconpath + ".temp", Iconpath);
}
filepath = Iconpath;
log.WriteLogFile(filepath, "Icon");
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
return false;
}
return true;
}
/// <summary>
/// 下载图片
/// </summary>
/// <param name="path">文件下载地址</param>
/// <param name="folderName">文件夹名称</param>
/// <param name="filename">应用程序文件名(不带扩展名)</param>
/// <returns>下载成功标志</returns>
public bool DownLoadImage(string path, string folderName, ref string filename)
{
try
{
var httpPath = path.Substring(0, path.IndexOf("://") + 3);
var fileBackPath = path.Substring(path.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/");
path = httpPath + fileBackPath;
string Iconpath = string.Empty;//文件保存的路径
var names = path.Split('/');
if (names.Length > 0)
{
filename = names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.'));
}
else
{
filename = path.Substring(path.LastIndexOf("/"));
}
//if (path.Contains("/"))
//{
// filename = path.Substring(path.LastIndexOf("/") + 1, path.Length - path.LastIndexOf("/") - 1);
//}
//else
//{
// filename = path;
//}
string fpath = AppDomain.CurrentDomain.BaseDirectory + "/" + folderName;
if (!Directory.Exists(fpath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(fpath);
directoryInfo.Create();
}
Iconpath = fpath + "/" + filename;
filename = Iconpath;
if (File.Exists(Iconpath))
{
return true;
}
if (File.Exists(Iconpath + ".temp"))
{
File.Delete(Iconpath + ".temp");
}
//下载应用程序压缩文件
if (!File.Exists(Iconpath + ".temp"))
{
try
{
using (Stream fileStream = new FileStream(Iconpath + ".temp", FileMode.OpenOrCreate))
{
fileStream.Seek(fileStream.Length, SeekOrigin.Current);
log.WriteLogFile(path, "HttpClient");//服务器地址
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
request.AddRange(fileStream.Length);
//下载文件
HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
using (Stream netStream = respone.GetResponseStream())
{
long totalDownloadedByte = 0;
byte[] read = new byte[1024];
int realReadLen = netStream.Read(read, 0, read.Length);
while (realReadLen > 0)
{
totalDownloadedByte = realReadLen + totalDownloadedByte;
fileStream.Write(read, 0, realReadLen);
realReadLen = netStream.Read(read, 0, read.Length);
System.Windows.Forms.Application.DoEvents();
}
netStream.Close();
}
fileStream.Close();
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
//File.delete(Iconpath + ".temp", Iconpath);
return false;
}
//删除temp文件
if (File.Exists(Iconpath))
{
File.Delete(Iconpath);
}
File.Move(Iconpath + ".temp", Iconpath);
filename = Iconpath;
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
return false;
}
return true;
}
public bool DownLoadBGImage(string path, string folderName)
{
try
{
string filename = string.Empty;
var httpPath = path.Substring(0, path.IndexOf("://") + 3);
var fileBackPath = path.Substring(path.IndexOf("://") + 3).Replace("//", "/").Replace("\\", "/");
path = httpPath + fileBackPath;
string Iconpath = string.Empty;//文件保存的路径
filename = "bg.png";
//if (path.Contains("/"))
//{
// filename = path.Substring(path.LastIndexOf("/") + 1, path.Length - path.LastIndexOf("/") - 1);
//}
//else
//{
// filename = path;
//}
string fpath = AppDomain.CurrentDomain.BaseDirectory + "/" + folderName;
if (!Directory.Exists(fpath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(fpath);
directoryInfo.Create();
}
foreach (FileInfo file in (new DirectoryInfo(fpath)).GetFiles())
{
file.Attributes = FileAttributes.Normal;
file.Delete();
}
Iconpath = fpath + "/" + filename;
filename = Iconpath;
if (File.Exists(Iconpath))
{
return true;
}
if (File.Exists(Iconpath + ".temp"))
{
File.Delete(Iconpath + ".temp");
}
//下载应用程序压缩文件
if (!File.Exists(Iconpath + ".temp"))
{
try
{
using (Stream fileStream = new FileStream(Iconpath + ".temp", FileMode.OpenOrCreate))
{
fileStream.Seek(fileStream.Length, SeekOrigin.Current);
log.WriteLogFile(path, "HttpClient");//服务器地址
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
request.AddRange(fileStream.Length);
//下载文件
HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
using (Stream netStream = respone.GetResponseStream())
{
long totalDownloadedByte = 0;
byte[] read = new byte[1024];
int realReadLen = netStream.Read(read, 0, read.Length);
while (realReadLen > 0)
{
totalDownloadedByte = realReadLen + totalDownloadedByte;
fileStream.Write(read, 0, realReadLen);
realReadLen = netStream.Read(read, 0, read.Length);
System.Windows.Forms.Application.DoEvents();
}
netStream.Close();
}
fileStream.Close();
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
//File.delete(Iconpath + ".temp", Iconpath);
return false;
}
//删除temp文件
if (File.Exists(Iconpath))
{
File.Delete(Iconpath);
}
File.Move(Iconpath + ".temp", Iconpath);
filename = Iconpath;
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "HttpClient");
return false;
}
return true;
}
public string UpLoadNew(string url, string path)
{
try
{
HttpWebRequest Request1 = (HttpWebRequest)System.Net.WebRequest.Create(url);
HttpWebResponse Response1 = (HttpWebResponse)(WebResponse)Request1.GetResponse();
System.IO.BinaryReader sr1 = new BinaryReader(Response1.GetResponseStream());
long fileLenth1 = Response1.ContentLength;
byte[] content1 = sr1.ReadBytes((Int32)fileLenth1);
FileStream so1 = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
BinaryWriter fileWriter1 = new BinaryWriter(so1);
fileWriter1.Write(content1, 0, (Int32)fileLenth1);
content1 = null;
Response1.Close();
fileWriter1.Flush();
fileWriter1.Close();
so1.Close();
return true.ToString();
}
catch (Exception ex)
{
return false.ToString() + ex.Message;
}
}
public string UpLoadTxt(string url, string path, string name)
{
try
{
HttpWebRequest Request1 = (HttpWebRequest)System.Net.WebRequest.Create(url);
HttpWebResponse Response1 = (HttpWebResponse)(WebResponse)Request1.GetResponse();
System.IO.BinaryReader sr1 = new BinaryReader(Response1.GetResponseStream());
long fileLenth1 = Response1.ContentLength;
byte[] content1 = sr1.ReadBytes((Int32)fileLenth1);
if (File.Exists(url)) { return ""; }
FileStream so1 = new FileStream(path + "\\" + name, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
BinaryWriter fileWriter1 = new BinaryWriter(so1);
fileWriter1.Write(content1, 0, (Int32)fileLenth1);
content1 = null;
Response1.Close();
fileWriter1.Flush();
fileWriter1.Close();
so1.Close();
return true.ToString();
}
catch (Exception ex)
{
return false.ToString() + ex.Message;
}
}
/// <summary>
///
/// </summary>
/// <param name="url">地址</param>
/// <param name="method">方法</param>
/// <param name="param">json参数</param>
/// <returns></returns>
public string WebServiceApppost(string param)
{
App app = ((App)Application.Current);
//转换输入参数的编码类型,获取bytep[]数组
byte[] byteArray = Encoding.UTF8.GetBytes(param);
//初始化新的webRequst
//1. 创建httpWebRequest对象
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
log.WriteLogFile("SendUrl:" + url, "HttpClient");
log.WriteLogFile("SendMessage:" + param, "HttpClient");
//2. 初始化HttpWebRequest对象
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
//webRequest.ProtocolVersion =
webRequest.ContentLength = byteArray.Length;
//3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
//4. 读取服务器的返回信息
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
php.Close();
response.Close();
log.WriteLogFile("RecvMessage:" + phpend, "HttpClient");
return phpend;
}
/// <summary>
/// http协议上传文件
/// </summary>
/// <param name="url"></param>
/// <param name="path"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string path, string param)
{
log.WriteLogFile("上传图片-平台地址为:" + url);
log.WriteLogFile("上传图片-本地位置:" + path);
byte[] byteArray = Encoding.UTF8.GetBytes(param.Length.ToString().PadLeft(6, '0') + param);
log.WriteLogFile("参数:" + param.Length.ToString().PadLeft(6, '0') + param);
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
string len = ASCII.GetString(byteArray,0,6);
string mes = ASCII.GetString(byteArray, 6, int.Parse(len));//@"E:\Test\回单机单机版\MultifuncSelfHelpterminal\bin\Release\CommonPic\ADpic\admin.jpg"
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
//FileStream fs1 = new FileStream("E:\\1234.jpg", FileMode.Create);
//fs1.Write(bArr, 0, bArr.Length);
//fs1.Flush();
//fs1.Dispose();
//MessageBox.Show(len + " " + mes);
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
//string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "charset=utf-8";
//request.ContentType = "application/json;charset=utf-8;boundary=" + boundary;
//byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
//byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + 1);
//请求头部信息
//StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
//byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
//StringBuilder sbType = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"type\"\r\nContent-Type:text/plain\r\n\r\n" + "1" + "\r\n"));
//byte[] strType = Encoding.UTF8.GetBytes(sbType.ToString());
Stream postStream = request.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
// stream.Read(bytes, 0, bytes.Length);
// stream.Dispose();
return content;
}
/// <summary>
/// http上传
/// </summary>
//public static string HttpUploadFile(string url, string path)
//{
// // 设置参数
// HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// CookieContainer cookieContainer = new CookieContainer();
// request.CookieContainer = cookieContainer;
// request.AllowAutoRedirect = true;
// request.Method = "POST";
// string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
// request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
// byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
// byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
// int pos = path.LastIndexOf("\\");
// string fileName = path.Substring(pos + 1);
// //请求头部信息
// StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
// byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
// FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
// byte[] bArr = new byte[fs.Length];
// fs.Read(bArr, 0, bArr.Length);
// fs.Close();
// Stream postStream = request.GetRequestStream();
// postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
// postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// postStream.Write(bArr, 0, bArr.Length);
// postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
// postStream.Close();
// //发送请求并获取相应回应数据
// HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// //直到request.GetResponse()程序才开始向目标网页发送Post请求
// Stream instream = response.GetResponseStream();
// StreamReader sr = new StreamReader(instream, Encoding.UTF8);
// //返回结果网页(html)代码
// string content = sr.ReadToEnd();
// return content;
//}
public void SaveImg(string strPath, Bitmap img)
{
//保存图片到目录
if (Directory.Exists(strPath))
{
//文件名称
string guid = Guid.NewGuid().ToString().Replace("-", "") + ".png";
img.Save(strPath + "/" + guid, System.Drawing.Imaging.ImageFormat.Png);
}
else
{
//当前目录不存在,则创建
Directory.CreateDirectory(strPath);
}
}
public bool CheckImageIsExists(string path, string folderName, ref string filename)
{
path = path.Replace("\\", "/");
string Iconpath = string.Empty;//文件保存的路径
var names = path.Split('/');
if (names.Length > 0)
{
filename = names[names.Length - 2] + names[names.Length - 1].Substring(names[names.Length - 1].LastIndexOf('.'));
}
else
{
filename = path.Substring(path.LastIndexOf("/"));
}
string fpath = AppDomain.CurrentDomain.BaseDirectory + "/" + folderName;
if (!Directory.Exists(fpath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(fpath);
directoryInfo.Create();
}
Iconpath = fpath + "/" + filename;
filename = Iconpath;
//判断文件是否存在
if (File.Exists(Iconpath))
{
return true;
}
else
{
return false;
}
}
}
}