Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 .:(
Posted

C#
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

C#
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;
        }
    }
 
Share this answer
 
v2
Comments
Aditya Chauhan 14-Apr-15 7:51am    
thanks for the reply ..i will check i found something then i will discuss again
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();

}
 
Share this answer
 
Comments
Richard Deeming 14-Apr-15 12:09pm    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Deepak Kanswal Sharma 14-Apr-15 12:20pm    
It works fine this way. What's the other way out??
Aditya Chauhan 5-May-15 6:36am    
ya it is Deepak Kanswal Sharma i am not just upload the images with in the database
i was doing upload system files directly to the server

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900