簡體   English   中英

FTP上傳圖片

[英]FTP Upload image

我想知道這段代碼有什么問題? 我在000webhost上托管ftp,我想上傳圖像,程序中的用戶使用openfiledialog功能從該計算機上打開該圖像

打開圖像的按鈕:

        OpenFileDialog open = new OpenFileDialog();
        if (open.ShowDialog() == DialogResult.OK)
        {
            Bitmap bit = new Bitmap(open.FileName);
            pictureBox1.Image = bit;
            pictureBox2.Image = bit;
            bit.Dispose();
            string fullPath = open.FileName;
            string fileName = open.SafeFileName;
            string path = fullPath.Replace(fileName, "");
            User.Details.UpLoadImage(fullPath);
        }

上傳代碼:

try
        {
            String sourcefilepath = source; // e.g. “d:/test.docx”
            String ftpurl = "ftp://www.locu.site90.com/public_html/"; // e.g. ftp://serverip/foldername/foldername
            String ftpusername = "********"; // e.g. username
            String ftppassword = "********"; // e.g. password
            string filename = Path.GetFileName(source);
            string ftpfullpath = ftpurl;
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
            ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);

            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.Method = WebRequestMethods.Ftp.UploadFile;

            FileStream fs = File.OpenRead(source);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();

            Stream ftpstream = ftp.GetRequestStream();
            ftpstream.Write(buffer, 0, buffer.Length);
            ftpstream.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

我不斷收到錯誤消息“請求的URI對於此FTP命令無效”,第二個錯誤是“遠程服務器返回錯誤:(530)未登錄。”

由於您正在上傳。 FTP網址中需要目標文件名。 看起來這是您可能要對以下行進行的處理:

string ftpfullpath = ftpurl;

嘗試將其更改為:

string ftpfullpath = ftpurl + filename;

對於未登錄的錯誤,某些托管公司僅允許安全連接。 您可以嘗試將以下行添加到代碼中:

ftp.EnableSsl = true;

我正在使用此方法,並且運行良好:

public static void UpLoadImage(string image, string targeturl)
        {
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.website.com/images/" + targeturl);
            req.UseBinary = true;
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.Credentials = new NetworkCredential("user", "pass");
            byte[] fileData = File.ReadAllBytes(image);
            req.ContentLength = fileData.Length;
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(fileData, 0, fileData.Length);
            reqStream.Close();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM