【问题标题】:I want to upload files with a C# windows forms project to a webserver我想将带有 C# windows 窗体项目的文件上传到网络服务器
【发布时间】:2022-03-30 06:01:39
【问题描述】:

我想使用 Windows 窗体创建一个 C# 应用程序,让我可以将文件上传到网络服务器,我看过很多教程,但每个人都证明对解决我的问题无用。

在我的项目中,我在上传按钮中有下一个代码

 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/

How to upload a file in window forms?

【问题讨论】:

  • 您展示的代码实际上就是您在 WinForms 方面所需要的...您还需要需要上传的服务器、正确的文件位置和正确的目标 url - 但目前还不清楚您会遇到什么样的错误正对着你的帖子。
  • 如果我使用该代码,它实际上会运行程序,但它不会将文件保存在指定的位置,我试图将其更改为 C:\ 但它会发生同样的事情我会尝试用你告诉我的参数,看看我能不能得到一些结果谢谢

标签: c# web-services visual-studio


【解决方案1】:

使用 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.");
         }
   }
}

【讨论】:

    【解决方案2】:

    在窗口中:

    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;
    }
    

    【讨论】:

    • 在服务器端,我想在我的项目中添加代码。
    • 如果服务器端是 PHP 而不是 ASP 怎么办?
    【解决方案3】:

    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 进行上传,只有在确实有必要解决我的问题时
    • +1。 @user3353954 - 你需要在localhost:8080 上接受 POST HTTP 请求的东西。 ASP.Net 是 C# 社区中广泛使用的 HTTP 堆栈(与 .Net 框架/Windows 一起提供),因此您将看到的大多数 HTTP 处理示例都使用 ASP.Net。绝对可以使用任何其他 HTTP 服务器 - UploadFile 发送的 POST 请求中绝对没有 ASP.Net 特定的内容。
    【解决方案4】:

    你应该在win app中设置

    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的读写权限

    【讨论】:

      【解决方案5】:

      在 Controllers 文件夹中创建一个简单的 API Controller 文件并将其命名为 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");
          }
      

      祝你好运

      【讨论】:

        猜你喜欢
        • 2010-12-16
        • 2011-01-09
        • 2017-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        相关资源
        最近更新 更多