简体   繁体   English

在ASP.NET中上传多个文件

[英]Multiple File Upload in ASP.NET

I'm creating a FTP client that will allow me upload files to a determined server picked from a combobox. 我正在创建一个FTP客户端,它将允许我将文件上传到从组合框中选择的确定的服务器。 My code works for a single file but trying to adapt it for more than one file has been challenging. 我的代码适用于单个文件,但是要使其适应多个文件一直很困难。 I've read about asynchronous uploads but I can't get it through my head so any help will be greatly appreciated. 我已经阅读了有关异步上传的内容,但是我无法理解,因此非常感谢您的帮助。

UPLOAD METHOD: 上载方法:

private void upload(string filepath, string address, string username, string password)
    {
            //CONNECT
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address + "/" + Path.GetFileName(filepath));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.KeepAlive = false;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            MessageBox.Show(response.WelcomeMessage + " to " + comboBox1.Text + " SERVER");
            //PREPARE FILE
            FileStream stream = File.OpenRead(filepath);
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();
            //UPLOAD FILE
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();
            MessageBox.Show("Upload complete on " + comboBox1.Text + " SERVER " + response.StatusDescription);

       }

I put the files I want to upload into a ListBox, this is the code: 我将要上传的文件放入列表框,这是代码:

 private void button2_Click(object sender, EventArgs e)
    {
        //THIS WAS FOR SINGLE FILE UPLOAD
        //if (openFileDialog1.ShowDialog() == DialogResult.OK)
        //textBox1.Text = openFileDialog1.FileName;

       //MULTIPLE FILE UPLOAD
        OpenFileDialog openFiles = new OpenFileDialog();
        openFiles.Filter = "PDF, XML, TXT Files(*.pdf;*.xml;*.txt)|*.pdf;*.xml;*.txt|All Files(*.*)|*.*";
        openFiles.Multiselect = true;
        //openFiles.InitialDirectory = "C:\\";
        //openFiles.RestoreDirectory = true;
        openFiles.Title = "Select Files";

        if (openFiles.ShowDialog() == DialogResult.OK)
        {
            foreach (string file in openFiles.FileNames)
            {
                listBox1.Items.Add(System.IO.Path.GetFileName(file));
            }
        }              

    }

Now, whenever I click "upload" I can connect to the server but It won't transfer the files the error is very straight forward: 现在,每当我单击“上传”时,我都可以连接到服务器,但是它不会传输文件,因此错误非常简单:

Could not find file 'C:\\Users\\me\\documents\\visual studio 2010\\Projects\\projectname\\project\\bin\\Debug\\openFileDialog1'. 找不到文件'C:\\ Users \\ me \\ documents \\ Visual Studio 2010 \\ Projects \\ projectname \\ project \\ bin \\ Debug \\ openFileDialog1'。

But I can't get through this part. 但是我无法理解这一部分。 How can I reference the filepath I want from the ListBox? 如何从ListBox引用所需的文件路径? This is my "upload_click" code, It's just one of the 3 servers I can access, but once i get the first one working, the other ones should be easy. 这是我的“ upload_click”代码,它只是我可以访问的3台服务器之一,但是一旦我使第一个服务器正常工作,其他服务器就应该很容易了。

 private void button1_Click(object sender, EventArgs e)
    {
        if (comboBox1.Text == "server" && listBox1.Items.Count > 0)
        {
            while (listBox1.Items.Count > 0)
            {
                upload(openFileDialog1.FileName, "ftp://000.000.0.000", "username", "password");
                listBox1.Items.RemoveAt(0);
            }
            textBox1.Text = " ";
            comboBox1.Text = "Select Server...";
            pictureBox1.Image = null;
            //listBox1.Items.Clear();
        }

I feel like its just a simple thing to achieve, but I can't see it. 我觉得这只是一件简单的事情,但我看不到。

What am I doing wrong? 我究竟做错了什么?

When you populate the listbox, you are stripping away the path and just including the filename. 填充列表框时,您将删除路径,仅包含文件名。

When you go to upload, you are using just the filename and the path is missing so the program looks in the default directory. 上载时,您仅使用文件名,并且缺少路径,因此该程序在默认目录中查找。

To verify, leave the full path of the filename in the listbox and see if it works. 要进行验证,请在列表框中保留文件名的完整路径,然后查看其是否有效。

To fix, you'll have to save the full paths somewhere if you don't want them displayed in the listbox. 要解决此问题,如果您不希望将完整路径显示在列表框中,则必须将其保存在某处。

Adding to Steve's answer: 添加到史蒂夫的答案:

I created a list List<string> fullFileName to save the full path of the files. 我创建了一个列表List<string> fullFileName来保存文件的完整路径。 Then when opening OpenFileDialog I saved the the full path with 然后,当打开OpenFileDialog我将完整路径保存为

fullFileName = new List<string>(openFiles.FileNames)

then for each file selected I added the file name in my listBox stripping away the path with listBox1.Items.Add(Path.GetFileNameWithoutExtension(file)) 然后对于每个选择的文件,我在listBox添加文件名,并使用listBox1.Items.Add(Path.GetFileNameWithoutExtension(file))路径

Then for the upload method parameters I just used the paths I had stored in my list 然后对于上upload方法参数,我只使用了存储在列表中的路径

fullFileName[listBox1.SelectedIndex]

And changed request.KeepAlive = false; 并更改了request.KeepAlive = false; to request.KeepAlive = true; request.KeepAlive = true; because I am planning to send large amounts of files, if I kept the connection alive for that long it would've died after some time, so I thought it was more advisable to open and close the request for each file uploaded. 因为我计划发送大量文件,所以如果我将连接保持活动状态这么长时间,它将在一段时间后消失,因此,我建议打开和关闭每个上载文件的请求是更可取的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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