Web Services 我要将含有C# Windows窗体项目的文件上载到Web服务器

mwkjh3gx  于 2022-11-15  发布在  C#
关注(0)|答案(5)|浏览(152)

我想创建一个C#应用程序使用窗口窗体,让我上传文件到一个网络服务器,我已经看到了很多教程,他们每个人都证明是无用的,以解决我的问题。
在我的项目中,我在上传按钮中有下一个代码

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

从这里我有几个错误,一个尝试多个想法,我的一些更常见的错误是404找不到或innaccessible路径,也有时它doenst显示我一个错误和工程,但文件不保存在指示的路径.
下面是我用来解决这个问题的一些链接: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?

hmae6n7t

hmae6n7t1#

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

vcudknz32#

在窗口中:

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

qgelzfjb3#

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>
pprl5pva

pprl5pva4#

您应该在WinApp中设置

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

up9lanfz

up9lanfz5#

在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");
    }

古德勒克

相关问题