lemunk
lemunk

Reputation: 2636

asp.net image source from ftp address

Using C# ASP.Net and visual Studio 2012 ultimate.

I've re-used some code from my form. to download an image from an ftp server.

public class FTPdownloader
{
    public Image Download(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
    {
        FtpWebRequest reqFTP;
        Image tmpImage = null;
        try
        {
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();

            tmpImage = Image.FromStream(ftpStream);

            ftpStream.Close();
            //outputStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }
        return tmpImage;
    }
}

Works great and all I do is call it like this on my form.

imgPart.Image = ftpclass.Download("" + "" + ".jpg", "address/images", "user", "pass");

Now this works great for winforms. My new project is an asp.net webform. I need it to do the same thing. I have re-used this code and seems ok, but when i call the method to img.Image i find img.Image does not exist in asp.net. Basically im returning an image and the closest thing i can find is a Img.ImageUrl which of course is a string.

So im Hoping this is a slight change to this code something in the call im missing (new to asp.net ).

Any help would be great. Thanks guys!

Upvotes: 1

Views: 4063

Answers (1)

Scott
Scott

Reputation: 21511

You have a conflict between the System.Drawing.Image returned by your download function and the Image control (System.Web.UI.Webcontrols.Image) of ASP.NET.

You can simplify the issue, by modifying your FTP download function slightly, so that it downloads and save the file ready for use by your Image web control.

Change your download function to:

private void Download(string fileName, string ftpServerIP, string ftpUserID, string ftpPassword, string outputName)
{
    using(WebClient request = new WebClient())
    {
        request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        byte[] fileData = request.DownloadData(string.Format("ftp://{0}{1}", ftpServerIP, filename));

        using(FileStream file = File.Create(Server.MapPath(outputName)))
        {
            file.Write(fileData, 0, fileData.Length);
        }
    }
}

The you can use this code to get your image:

// Download image
ftpclass.Download("/images/myimage.jpg", "server-address", "user", "pass", "/mysavedimage.jpg");

// Now link to the image
imgPart.ImageUrl = "/mysavedimage.jpg";

Hope this helps.

Upvotes: 2

Related Questions