使用ASP.NET上传文件

本文关键字:文件 NET ASP 使用 | 更新日期: 2023-09-27 18:15:06

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

上面的代码将文件上传到Filesonic服务器,但是我想使用c#编程地做到这一点,基本上我的要求是程序创建表单和文件控件,并将文件发送到action属性中提到的Filesonic服务器URL ..

我浏览了很多链接都没有成功,我浏览了下面的链接也没有成功。

使用HTTPWebrequest (multipart/form-data)上传文件

使用ASP.NET上传文件

只要服务器可以在files[]数组之外接受文件,下面的代码将把文件上传到服务器。

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
    }

在这种情况下,您对表单的操作将指向您在asp.net服务器上自己的页面。你将使用http将一个文件发送回你的asp.net服务器,然后你将把它保存在内存中或写到一个临时目录,然后你可以HttpWebRequest将文件发送到filesonic服务器。

在你的情况下,你也可以直接使用HttpWebRequest,一个快速的例子,我可以找到在这里

您可以使用FTP凭证将文件上传到服务器这里,path是指本地文件路径或源文件&DestinationPath是服务器路径,您必须上传文件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();