我想知道这段代码有什么问题?我在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)未登录。”
答案 0 :(得分:1)
因为您正在上传。 FTP网址中需要目标文件名。看起来这就是你打算用以下几行做的事情:
string ftpfullpath = ftpurl;
尝试将其更改为:
string ftpfullpath = ftpurl + filename;
对于未登录的错误,某些托管公司仅允许安全连接。您可以尝试在代码中添加以下行:
ftp.EnableSsl = true;
答案 1 :(得分:0)
我正在使用这种方法,而且效果很好:
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();
}