简体   繁体   中英

Upload files using ASP.NET

<form action="http://s0.filesonic.com/abc" method="post" enctype="multipart/form-data">
    <input type="file" name="files[]" />
    <button type="submit">submit</button>
</form>

The above code uploads the files to file sonic server, but I want to do this using programmatically using C#, basically my requirement is that the program creates the form and file control and sends the file to the Filesonic server URL mentioned in action attribute..

I have gone through many links but with no success, I have gone through the following links with no success.

Upload files with HTTPWebrequest (multipart/form-data)

The following code will upload the file to the server as long as the server can accept it outside of files[] array.

WebRequest webRequest = WebRequest.Create("http://s0.filesonic.com/abc");
FileStream reader = new FileStream("file_to_upload", FileMode.Open);

byte[] data = new byte[reader.Length];
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data";
webRequest.ContentLength = reader.Length;
webRequest.AllowWriteStreamBuffering = "true";

reader.Read(data, 0, reader.Length);

using (var request = webRequest.GetRequestStream())
{
    request.Write(data, 0, data.Length);
    using (var response = webRequest.GetResponse())
    {
        //Do something with response if needed
    }

You can upload file to your server using FTP credentials Here , path means your local file path or source file & DestinationPath is server path where you have to upload file Ex. 'www.....com/upload/xxx.txt'

FtpWebRequest reqObj = (FtpWebRequest) WebRequest.Create(DestinationPath);                                   
reqObj.Method = WebRequestMethods.Ftp.UploadFile;                          
reqObj.Credentials = new NetworkCredential(FTP_USERNAME, FTP_PASSWORD);

byte[] fileContents = File.ReadAllBytes(path);   
reqObj.ContentLength = fileContents.Length;

Stream requestStream = reqObj.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
response.Close();

I that case your action on the form would point to your own page on your asp.net server. You are going to post a file back to your asp.net server using http, you will then either hold it in memory or write it to a temp directory, then you could HttpWebRequest to send the file to the filesonic server.

In your case you can also do form a post directly using HttpWebRequest, a quick sample that i could find is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM