爱吃酸菜鱼的猫

上传文件到服务器

1.选择要上传的文件,路径显示在ListBox里

private void btnSelect_Click(object sender, EventArgs e)
{
lbxFiles.Items.Clear();
OpenFileDialog file = new OpenFileDialog();
file.Multiselect = true;//允许选择多个文件
if (file.ShowDialog() == DialogResult.OK)
{
filen = Path.GetFileName(file.ToString());
lbxFiles.Items.AddRange(file.FileNames);
}
}

2.分部上传文件。

    (1),根据服务器端提供的接口参数,来拼接对应的参数值,并调用PostForm方法,实现上传。

/// <summary>
/// 上传文件
/// </summary>
/// <param name="data">资源数据</param>
public static string UpLoad(Dictionary<string, string> files)
{
string flag = string.Empty;
string errorMsg = string.Empty;
string jsonData = string.Empty;

_responseUploadFileFullName = "";

Dictionary<string, string> parameters = new Dictionary<string, string>();//目标接口参数,根据接口的定义,并不固定
parameters.Add("accessToken", ServerConfig.accessToken);
parameters.Add("apiId", "resource");//接口Id
parameters.Add("command", "uploadFile");//接口命令
parameters.Add("path", "/opt/resources/picture");//目标文件地址
string strUrl = string.Format("{0}/API.aspx", ServerConfig.serverUrl);//拼接Url,为服务器的地址。
string result = new HttpHelper().PostForm(strUrl, parameters, files);//调用上传文件的方法,内容在PostForm里,结果返回
if (!string.IsNullOrEmpty(result))
{
ResponseCode response = DeserializeObject<ResponseCode>(result);
if (response != null && (response.ErrorCode.ToString().Trim() == "0" || response.ErrorCode.ToString().Trim() == "561"))//561 文件已存在
{
if (response.Data == null || string.IsNullOrEmpty(response.Data.ToString()))
{
return "";
}
_responseUploadFileFullName = Path.Combine("/opt/resources/picture", response.Data.ToString());
}
}
return result;
}

      (2)使用Http post,进行文件上传(本以为上传文件,接口参数最起码要留有两个路径参数,但实际上是只需要一个服务器端的路径就可以了,把需要上传的文件转换成流,以流的方式,在进行http请求的时候,直接塞进去)

/// <summary>
/// 使用Post方法获取字符串结果
/// </summary>
/// <param name="url"></param>
/// <param name="_params">参数集合</param>
/// <param name="files">文件集合</param>
/// <param name="timeOut">默认20秒</param>
/// <returns></returns>
public string PostForm(string url, Dictionary<string, string> _params, Dictionary<string, string> files, int timeOut = 20000)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
#region 初始化请求对象
request.Method = "POST";
request.Timeout = timeOut;
request.Accept = accept;
request.KeepAlive = true;
request.UserAgent = userAgent;
request.Referer = url;
#endregion

string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
//请求流
var postStream = new MemoryStream();
#region 处理Form表单请求内容
//文件数据模板
string fileFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
//文本数据模板
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";

foreach (var param in _params)
{
string formdata = null;
byte[] formdataBytes = null;
formdata = string.Format(dataFormdataTemplate, param.Key, param.Value);
if (postStream.Length == 0)
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
else
formdataBytes = Encoding.UTF8.GetBytes(formdata);
postStream.Write(formdataBytes, 0, formdataBytes.Length);
}

foreach (var file in files)//把文件转换成流
{
byte[] formdataBytes = null;
string formdata = string.Format(fileFormdataTemplate, file.Key, file.Value);
if (postStream.Length == 0)
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
else
formdataBytes = Encoding.UTF8.GetBytes(formdata);
postStream.Write(formdataBytes, 0, formdataBytes.Length);
using (FileStream fileStream = new FileStream(file.Value, FileMode.Open, FileAccess.Read))//
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
}
//结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);

#endregion

request.ContentLength = postStream.Length;

#region 输入二进制流
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();

byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
postStream.Close();//关闭文件访问
}
#endregion

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}

  (3)接收经过post请求,返回的Json

先把Json转换成对象

/// <summary>
/// 将json字符转成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T DeserializeObject<T>(string json)
{
if (string.IsNullOrWhiteSpace(json))
return default(T);
return JsonConvert.DeserializeObject<T>(json);
}

//展示在指定的UI界面中,因服务器的接口限制,每次只允许上传一个文件。

private void btnUpLoad_Click(object sender, EventArgs e)
{
if (lbxFiles.Items.Count!=0)
{
if (lbxFiles.Items.Count==1)
{
Dictionary<string, string> files = new Dictionary<string, string>();
foreach (var item in lbxFiles.Items)
{
files.Add(Path.GetFileName(item.ToString()).ToString(), item.ToString());
}
string text = FunHelper.UpLoad(files);
string text1 = text.Replace("\"", "");

string[] array = text1.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string errCode = array[1].Split(new char[] {' ', ':', ',' }, StringSplitOptions.RemoveEmptyEntries)[1];
string errMess = array[2].Split(new char[] {' ', ':', ',' }, StringSplitOptions.RemoveEmptyEntries)[1];
string fileName = array[3].Split(new char[] { ' ',':', ',' }, StringSplitOptions.RemoveEmptyEntries)[1];
if (errCode=="0")
{
this.BeginInvoke(new Action(() =>
{
lbxFiles.Items.Clear();
lbxFiles.Items.Add(filen+" 文件上传成功");
}));
}
else
{
this.BeginInvoke(new Action(() =>
{
lbxFiles.Items.Clear();
lbxFiles.Items.Add(filen+" 文件上传失败");
}));
}

}
else
{
MessageBox.Show("每次只能上传一个文件" + "\r\n" + "请重新选择!");
}
}
else
{
MessageBox.Show("请选择要上传的文件");
}
}

posted on 2018-04-18 16:28  爱吃酸菜鱼的猫  阅读(130)  评论(0编辑  收藏  举报

导航