图像在FTP中损坏,二进制模式打开

本文关键字:二进制 模式 损坏 FTP 图像 | 更新日期: 2023-09-27 18:03:55

我在1月份就这个问题发了一篇帖子,但是这个问题一直没有解决。我一直在做一个程序,把它传到我的Youtube Teams网站上。由于某些奇怪的原因,生成的HTML代码可以正常工作并成功传输,但是图像却损坏了。我已经确保二进制模式设置为true并且权限都是正确的。

有人能帮我吗?

这是代码中与我的问题相关的部分:

namespace TMNGP_FTP
{
    partial class Form1
    {
        // some functions and properties for the form
        UriBuilder ftpurl;
        String ftpurlstr = "ftp://tmngp.heliohost.org";
        static String ftpusername = "*******";
        static String ftppassword = "*******";
        public static string GenerateFileName(string context)
        {
            return context + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
        }
        public void openpic_Click(object sender, System.EventArgs e)
        {
            //Wrap the creation of the OpenFileDialog instance in a using statement,
            //Rather than manually calling the dispose method to ensure proper disposal
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = "Open Image";
                dlg.Filter = "png files (*.png)|*.png";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    string folderName = @"c:'TMNGP_Web_Files";
                    string pathString = folderName + @"'htTemp";
                    pathString = pathString + @"'imgs";
                    if (!System.IO.Directory.Exists(pathString))
                    {
                        System.IO.Directory.CreateDirectory(pathString);
                    }
                    string destFileName = pathString + @"'" + dlg.SafeFileName.ToString();
                    System.IO.File.Copy(dlg.FileName, destFileName, true);
                    DisplImg.Image = new Bitmap(dlg.OpenFile());
                    DisplImg.ImageLocation = destFileName;
                }
            }
        }
        private FtpClient ftpnew = null;
        public void textgen_Click(object sender, System.EventArgs e)
        {
            string folderName = @"c:'TMNGP_Web_Files";
            string pathString = folderName + @"'htTemp";
            if (!System.IO.Directory.Exists(pathString))
            {
                System.IO.Directory.CreateDirectory(pathString);
            }
            string fileName = GenerateFileName("HT");
            pathString = pathString + @"'" + fileName;
            Console.WriteLine("Path to my file: {0}'n", pathString);
            if (!System.IO.File.Exists(pathString))
            {
                //System.IO.FileStream fs = System.IO.File.Create(pathString);
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
                {
                    file.WriteLine("<div class='simple_overlay' id='news_archive/" + DisplImg.ImageLocation.Substring(31) + "' style='display:none;'>");
                    file.WriteLine("<a class='close'></a>");
                    file.WriteLine("<img src='news_archive/" + DisplImg.ImageLocation.Substring(31) + "'/>");
                    file.WriteLine("<div class='details'>");
                    file.WriteLine("<h3> " + txtTitle.Text + " </h3>");
                    file.WriteLine("<h4> " + TxtInfo.Text + " </h4>");
                    file.WriteLine("<p>" + Desctext.Text + "</p>");
                    file.WriteLine("</div>");
                    file.WriteLine("</div>");
                }
                if(radioButton1.Checked)
                {
                    ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "NGP/news_archive/");
                    ftpurlstr = "/public_html/NGP/news_archive";
                }
                else
                {
                    ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "TM/news_archive/");
                    ftpurlstr = "/public_html/TM/news_archive";
                }
                try
                {
                    //string filenametwo = System.IO.Path.GetFullPath(@"c:'TMNGP_Web_Files'htTemp'"+fileName);
                    string filenamethree = System.IO.Path.GetFullPath(DisplImg.ImageLocation.ToString());
                    Console.WriteLine("{0}", filenamethree);
                    Console.WriteLine(pathString);
                    //string ftpfullpath = ftpurl;
                    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create((@"ftp://tmngp.heliohost.org" + ftpurlstr + fileName).ToString());
                    Console.WriteLine("{0}", ftpurl + fileName);
                    ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
                    ftp.KeepAlive = true;
                    ftp.UseBinary = true;
                    ftp.Method = WebRequestMethods.Ftp.UploadFile;
                    StreamReader sourceStreamone = new StreamReader(@"c:'TMNGP_Web_Files'htTemp'" + fileName);
                    byte[] fileContentsone = Encoding.UTF8.GetBytes(sourceStreamone.ReadToEnd());
                    sourceStreamone.Close();
                    ftp.ContentLength = fileContentsone.Length;
                    Stream requestStreamone = ftp.GetRequestStream();
                    requestStreamone.Write(fileContentsone, 0, fileContentsone.Length);
                    requestStreamone.Close();
                    FtpWebResponse ftpresponseone = (FtpWebResponse)ftp.GetResponse();
                    Console.WriteLine("Upload File Complete, status {0}", ftpresponseone.StatusDescription);
                    ftpresponseone.Close();
                }
                catch (WebException ex)
                {
                    throw ex;
                }
                try
                {
                    string imgfile = DisplImg.ImageLocation.Substring(31);
                    FtpWebRequest ftp2 = (FtpWebRequest)FtpWebRequest.Create((@"ftp://tmngp.heliohost.org" + ftpurlstr + imgfile).ToString());
                    ftp2.Credentials = new NetworkCredential(ftpusername, ftppassword);
                    ftp2.KeepAlive = true;
                    ftp2.UseBinary = true;
                    ftp2.Method = WebRequestMethods.Ftp.UploadFile;
                    StreamReader sourceStreamtwo = new StreamReader(DisplImg.ImageLocation.ToString());
                    byte[] fileContentstwo = Encoding.UTF8.GetBytes(sourceStreamtwo.ReadToEnd());
                    sourceStreamtwo.Close();
                    ftp2.ContentLength = fileContentstwo.Length;
                    Stream requestStreamtwo = ftp2.GetRequestStream();
                    requestStreamtwo.Write(fileContentstwo, 0, fileContentstwo.Length);
                    requestStreamtwo.Close();
                    FtpWebResponse ftpresponsetwo = (FtpWebResponse)ftp2.GetResponse();
                    Console.WriteLine("Upload File Complete, status {0}", ftpresponsetwo.StatusDescription);
                    ftpresponsetwo.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                MessageBox.Show("FTP Complete");
            }
            else
            {
                Console.WriteLine("File '"{0}'" already exists.", fileName);
                return;
            }
        }

        // a bunch of Windows Form Designer generated code ...
    }
}

图像在FTP中损坏,二进制模式打开

Ok,这段代码很难阅读,但是,当您声明Byte[] fileContentTwo时,看起来您正在对图像(sourceStreamTwo)使用Encoding.UTF8.GetBytes()。

编辑 -忘了说,你不需要StreamReader -使用FileStream代替:

FileStream sourceStreamtwo = new FileStream(DisplImg.ImageLocation.ToString(), FileMode.Open);

改为

Byte[] fileContentTwo;
using (BinaryReader br = new BinaryReader(sourceStreamtwo))
{
    fileContentsTwo = br.ReadBytes((int)sourceStreamtwo.Length);
    // rest of code that deals with sourceStreamTwo
}

注意,这假定您不是从网络中读取,因此您可能没有整个流可用,请参阅从流中创建字节数组

在。net 4或更高版本中,您可以使用Stream.CopyTo(),它更安全,因为它可以处理流中的中断-再次参见上面的问题和回答以获得更多信息。

你应该很好。编码是用于文本的,图像是二进制的。

还请考虑一些不同的命名约定为您的变量:)