Image.Write到FTP损坏了吗?

时间:2013-10-06 12:01:15

标签: c# ftp

我已经运行了这个代码并且它运行得非常好 - 直到几个星期后才决定它不想工作。

我不确定为什么它不起作用。

调整所选图像的大小,然后将其上传到服务器。但是,应用程序仅上传4.380kb的文件 - 无论我选择什么图像。 这与我保存的目录无关。

FTP帐户肯定具有权限,可以无问题地上传其他文件。因此,我认为上传图像的代码中的某些内容必定是问题?

UploadImage

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uploadLocation);
FileInfo toUpload = new FileInfo(fileToUpload);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream ftpStream = request.GetRequestStream();           

Image image = Image.FromFile(fileToUpload);
image = Tools.ScaleImage(image, 500, 360);
image.Save(ftpStream, ImageFormat.Jpeg);
image.Save(@"C:\Users\User\Desktop\image.jpg", ImageFormat.Jpeg);

认为它可能与我的调整大小代码有关,我将文件的副本保存到桌面 - 文件保存完好并按预期保存。

但是,这里的代码如下所示:

ScaleImage

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    return newImage;
}

正如我所说,使用完全相同的FTP凭据进入同一个文件夹,我可以使用ftp流上传其他文件......不知道为什么这已停止工作....


编辑: 如果有帮助,我已经添加了我的代码来上传文件(使用相同的ftp设置)。这工作正常 - 如何修改它以上传图像?

uploadfile:
FileStream file = File.OpenRead(fileToUpload);
                int length = 1024;
                byte[] buffer = new byte[length];
                int bytesRead = 0;

                totalToUpload = file.Length;
                try
                {
                    do
                    {
                        bytesRead = file.Read(buffer, 0, length);
                        ftpStream.Write(buffer, 0, bytesRead);
                        totalReadBytesCount += bytesRead;
                        var progress = totalReadBytesCount * 100.0 / totalToUpload;
                        backgroundWorker2.ReportProgress((int)progress);
                    }
                    while (bytesRead != 0);
                    file.Close();

1 个答案:

答案 0 :(得分:0)

尝试使用流上传它:

MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
byte[] imgBytes = ms.ToArray();

ftpstream.Write(imgBytes, 0, imgBytes.Length); 
ftpstream.Close(); 

你也可以尝试循环写作