如何在windows c中使用http web请求上传文件# [英] How can upload files using http web request in windows c#
本文介绍了如何在windows c中使用http web请求上传文件#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好专家,
我已经制作了一个Windows窗体应用程序和控制台exe也在这个我上传文件使用ftp web请求
但现在我想从它http web请求或htttps如何在c#
中提出任何建议?
bcz ftp不安全。:(
Hello Experts,
I have made a windows form application and console exe also in this i am upload files using ftp web request
but now i want to it from http web request or htttps how it is possible in c#
any suggestion?
bcz ftp is not secured .:(
推荐答案
string URL = "http://"+HostIP+"/some/path/to/website";
string boundary = "----" + System.Guid.NewGuid();
string Dateiname = Path.GetFileName(FileName);
// Read file data
FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
// Generate post objects
Dictionary<string,> postParameters = new Dictionary<string,>();
//postParameters.Add("name", "file");
postParameters.Add("file", new FormUpload.FileParameter(data, Dateiname, "application/octet-stream"));
// Create request and receive response
string postURL = URL;
string userAgent = "Someone";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);
// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
fullResponse = responseReader.ReadToEnd();
webResponse.Close();
连同
together with
public static class FormUpload
{
private static readonly Encoding encoding = Encoding.UTF8;
public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string,> postParameters)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
return PostForm(postUrl, userAgent, contentType, formData);
}
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
if (request == null)
{
throw new NullReferenceException("request is not a http request");
}
// Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userAgent;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
// You could add authentication here as well if needed:
request.PreAuthenticate = true;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("USER" + ":" + "PASSWORD")));
// Send the form data to the request.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
private static byte[] GetMultipartFormData(Dictionary<string,> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
needsCLRF = true;
if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
public class FileParameter
{
public byte[] File { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public FileParameter(byte[] file) : this(file, null) { }
public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
public FileParameter(byte[] file, string filename, string contenttype)
{
File = file;
FileName = filename;
ContentType = contenttype;
}
}
试用此代码: -
protected void Button1_Click(object sender,EventArgs e)
{
if(FileUpload1.HasFile)
{
uploadimage(FileUpload1,TextBox2);
}
if(FileUpload2.HasFile)
{
uploadimage(FileUpload2,TextBox3);
}
if( FileUpload3.HasFile)
{
uploadimage(FileUpload3,TextBox4);
}
if(FileUpload4.HasFile)
{
uploadimage(FileUpload4,TextBox5);
}
if(FileUpload5.HasFile)
{
uploadimage(FileUpload5,TextBox6);
}
if(FileUpload6.HasFile)
{
uploadimage(FileUpload6,TextBox7);
}
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),alertMessage,alert('Pictures Uploaded Successfully'),true);
}
public void uploadimage(FileUpload f1,TextBox t1)
{
string str = @data source = DEEPAKSHARMA-PC \ SQLEXPRESS;初始目录=新; integrated security = true;
SqlConnection con = new SqlConnection(str);
con.Open();
string s = Server。 MapPath(Img /)+ f1.FileName;
f1.SaveAs(s);
// SqlDataAdapter da = new SqlDataAdapter(从ddate选择计数(*)+ 1作为d,con);
// int a = Convert.ToInt32(select(count(*)+ 1)dd from ddate);
string query =插入date1 values('+ TextBox1.Text +','+ f1.FileName +','+ t1.Text +');
SqlCommand cmd = new SqlCommand(query,con);
cmd.ExecuteNonQuery();
con.Close();
}
Try this code:-
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
uploadimage(FileUpload1,TextBox2);
}
if (FileUpload2.HasFile)
{
uploadimage(FileUpload2,TextBox3);
}
if (FileUpload3.HasFile)
{
uploadimage(FileUpload3,TextBox4);
}
if (FileUpload4.HasFile)
{
uploadimage(FileUpload4,TextBox5);
}
if (FileUpload5.HasFile)
{
uploadimage(FileUpload5,TextBox6);
}
if (FileUpload6.HasFile)
{
uploadimage(FileUpload6,TextBox7);
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Pictures Uploaded Successfully')", true);
}
public void uploadimage(FileUpload f1, TextBox t1)
{
string str = @"data source=DEEPAKSHARMA-PC\SQLEXPRESS;initial catalog=new; integrated security=true";
SqlConnection con = new SqlConnection(str);
con.Open();
string s = Server.MapPath("Img/") + f1.FileName;
f1.SaveAs(s);
//SqlDataAdapter da = new SqlDataAdapter("Select count(*)+1 as d from ddate", con);
//int a = Convert.ToInt32("Select (count(*)+1) as d from ddate");
string query = "insert into date1 values('" + TextBox1.Text + "','" + f1.FileName + "','" + t1.Text + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
这篇关于如何在windows c中使用http web请求上传文件#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文