upload file to server

1. Select the file to upload, the path is displayed in the 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. Partial upload files.

    (1) According to the interface parameters provided by the server, the corresponding parameter values ​​are spliced, and the PostForm method is called to realize the upload.

/// <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>();//The target interface parameters, according to the definition of the interface, are not fixed
parameters.Add("accessToken", ServerConfig.accessToken);
parameters.Add(" apiId", "resource");//Interface Id
parameters.Add("command", "uploadFile");//Interface command
parameters.Add("path", "/opt/resources/picture");//target File address
string strUrl = string.Format("{0}/API.aspx", ServerConfig.serverUrl);//The splicing Url is the address of the server.
string result = new HttpHelper().PostForm(strUrl, parameters, files);//Call the method of uploading files, the content is in PostForm, the result returns
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) Use Http post to upload files (I thought that for uploading files, the interface parameters should have at least two path parameters, but in fact, only one server-side path is needed to convert the files to be uploaded into streams. , in a streaming way, when making an http request, plug it directly)

/// <summary>
/// Use Post method to get string result
/// </summary>
/// <param name="url"></param>
/// <param name="_params">parameter Collection</param>
/// <param name="files">File Collection</param>
/// <param name="timeOut">default 20 seconds</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 Initialize the request object
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");//Delimiter
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary );
//Request stream
var postStream = new MemoryStream();
#region Process Form form request content
//File data template
string fileFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form- data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
/ /text data template
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 Input binary stream
if (postStream != null)
{
postStream.Position = 0;
//Write directly to the stream
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) Receive the returned Json after the post request

Convert Json to object first

/// <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);
}

//Display in the specified UI interface. Due to the interface limitation of the server, only one file is allowed to be uploaded at a time.

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+"File upload failed");
}));
}

}
else
{
MessageBox.Show("Only one file can be uploaded at a time" + "\r\n" + "Please select again!") ;
}
}
else
{
MessageBox.Show("Please select the file to upload");
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324604212&siteId=291194637