使用C# Windows Forms项目将文件上传到Web服务器

3
我希望创建一个使用Windows窗体的C#应用程序,可以让我上传文件到Web服务器。我看了很多教程,但是每一个都无法解决我的问题。

在我的项目中,我在上传按钮中有以下代码:

 WebClient client = new WebClient();
        client.UploadFile("http://localhost:8080/", location);

从这里开始,我遇到了一些错误,并尝试了多种想法,其中一些常见的错误是404未找到或路径不可访问,有时它不会显示错误并工作,但文件不会保存在指定的路径中。
以下是我用来解决问题的一些链接: http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx http://www.c-sharpcorner.com/Blogs/8180/ 如何在窗体中上传文件?

你展示的代码基本上是WinForms需要的全部... 此外,你还需要一个接受上传文件的服务器、正确的文件位置和正确的目标URL - 但从你的帖子中很不清楚你正在面对什么样的错误。 - Alexei Levenkov
如果我使用那段代码,程序确实会运行,但它不会将文件保存在指定的位置,我尝试将其更改为C:\,但仍然出现相同的问题。我将尝试使用您告诉我的参数,看看是否能得到一些结果,谢谢。 - FranGil
5个回答

2
使用C#从本地硬盘上传文件到FTP服务器。
private void UploadFileToFTP()
{
   FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");

   ftpReq.UseBinary = true;
   ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
   ftpReq.Credentials = new NetworkCredential("user", "pass");

   byte[] b = File.ReadAllBytes(@"E:\sample.txt");
   ftpReq.ContentLength = b.Length;
   using (Stream s = ftpReq.GetRequestStream())
   {
        s.Write(b, 0, b.Length);
   }

   FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

   if (ftpResp != null)
   {
         if(ftpResp.StatusDescription.StartsWith("226"))
         {
              Console.WriteLine("File Uploaded.");
         }
   }
}

1
在Windows中:
private void uploadButton_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    var dialogResult = openFileDialog.ShowDialog();    
    if (dialogResult != DialogResult.OK) return;              
    Upload(openFileDialog.FileName);
}

private void Upload(string fileName)
{
    var client = new WebClient();
    var uri = new Uri("http://www.yoursite.com/UploadMethod/");  
    try
    {
        client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
        var data = System.IO.File.ReadAllBytes(fileName);
        client.UploadDataAsync(uri, data);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

在服务器中:
[HttpPost]
public async Task<object> UploadMethod()
{
    var file = await Request.Content.ReadAsByteArrayAsync();
    var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
    var filePath = "/upload/files/";
    try
    {
        File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);           
    }
    catch (Exception ex)
    {
        // ignored
    }

    return null;
}

在服务器端,我应该在我的项目中添加代码。 - Md. Didarul Islam
1
如果服务器端是 PHP,而不是 ASP 呢? - Ahmed Suror

0

你应该在 Windows 应用程序中进行设置

WebClient myWebClient = new WebClient();

string fileName = "File Address";
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);

// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

然后为SubDir设置读写权限。


0
在Controllers文件夹中创建一个简单的API控制器文件,并将其命名为UploadController。
让我们通过添加一个新的操作来修改该文件,该操作将负责上传逻辑:
 [HttpPost, DisableRequestSizeLimit]
    public IActionResult UploadFile()
    {
        try
        {
            var file = Request.Form.Files[0];
            string folderName = "Upload";
            string webRootPath = _host.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);
            string ext = Path.GetExtension(file.FileName);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file.Length > 0)
            {
                string fileName = "";
                string name = Path.GetFileNameWithoutExtension(file.FileName);
                string fullPath = Path.Combine(newPath, name + ext);
                int counter = 2;
                while (System.IO.File.Exists(fullPath))
                {
                    fileName = name + "(" + counter + ")" + ext;
                    fullPath = Path.Combine(newPath, fileName);
                    counter++;
                }
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                return Ok();
            }
            return Ok();
        }
        catch (System.Exception ex)
        {
            return BadRequest();
        }
    }

我们正在使用POST操作来处理上传相关的逻辑,并禁用请求大小限制。同时,在Winform中使用以下代码:

 private void Upload(string fileName)
    {
        var client = new WebClient();
        var uri = new Uri("https://localhost/api/upload");
        try
        {
            client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
            client.UploadFileAsync(uri, directoryfile);
            client.UploadFileCompleted += Client_UploadFileCompleted;
            
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
    {
        MessageBox.Show("done");
    }

祝你好运


0

Winform

string fullUploadFilePath = @"C:\Users\cc\Desktop\files\test.txt";
string uploadWebUrl = "http://localhost:8080/upload.aspx";
client.UploadFile(uploadWebUrl , fullUploadFilePath );

在asp.net中创建upload.aspx如下:

<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {

    foreach(string f in Request.Files.AllKeys) {
        HttpPostedFile file = Request.Files[f];
        file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
    }   
}

</Script>
<html>
<body>
<p> Upload complete.  </p>
</body>
</html>

你为什么使用ASP.net?? 为了更好地理解我的问题,我可以不使用ASP.net进行下载。 如果没有必要解决我的问题,我不想使用ASP.net进行上传。 - FranGil
+1. @user3353954 - 你需要一个能够在localhost:8080上接受POST HTTP请求的东西。ASP.Net是C#社区中广泛使用的HTTP堆栈(因为它随着.Net框架/Windows一起提供),所以你会看到大多数处理HTTP的示例都使用ASP.Net。当然,你也可以使用任何其他HTTP服务器——在由UploadFile发送的POST请求中,绝对没有任何ASP.Net特定的内容。 - Alexei Levenkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接