如何在 C# 中将图像保存在 FTP 服务器中

本文关键字:保存 存在 FTP 服务器 图像 | 更新日期: 2023-09-27 18:33:07

如何在FTP服务器中将流数据另存为图像?

 FileInfo fileInf = new FileInfo("1" + ".jpg");
                        string uri = "ftp://" + "hostip//Data//" + fileInf.Name;
                        FtpWebRequest reqFTP;
                        // Create FtpWebRequest object from the Uri provided
                        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(
                             "ftp://" + "ipaddress//Data//" + fileInf.Name));
                        // Provide the WebPermission Credintials
                        reqFTP.Credentials = new NetworkCredential("username",
                                                              "password");
                        // By default KeepAlive is true, where the control connection is 
                        // not closed after a command is executed.
                        reqFTP.KeepAlive = false;
                        // Specify the command to be executed.
                        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                        // Specify the data transfer type.
                        reqFTP.UseBinary = true;
                        // Notify the server about the size of the uploaded file
                        //reqFTP.ContentLength = fileInf.Length; ???
                        using (var img = Image.FromStream(image))
                        {
                            img.Save(adduser.User_Id + ".jpg", ImageFormat.Jpeg);
                        }

你能告诉我吗?

如何在 C# 中将图像保存在 FTP 服务器中

您需要将数据

(图像)放入字节数组中,然后发送。FtpWebRequest.GetResponse 文档示例显示了基础知识,尽管它附加了一个文件。其他一切都与您正在做的事情相关(您将用上传文件替换附加文件)。

要将图像放入字节数组中,您可以编写:

byte[] imageBuffer = File.ReadAllBytes(imageFileName);

其他所有内容都应与文档示例非常相似。

以下是从 FTP 服务器下载文件的示例代码

Uri url = new Uri("ftp://ftp.demo.com/Image1.jpg");
if (url.Scheme == Uri.UriSchemeFtp)
{
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
    //Set credentials if required else comment this Credential code
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
    objRequest.Credentials = objCredential;
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
    byte[] buffer = new byte[16 * 1024];
    int len = 0;
    FileStream objFS = new FileStream(Server.MapPath("Image1.jpg"), FileMode.Create, FileAccess.Write, FileShare.Read);
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        objFS.Write(buffer, 0, len);
    }
    objFS.Close();
    objResponse.Close();
}