将base64String保存为FTP服务器上的图像,保存损坏的文件

时间:2016-01-27 07:41:21

标签: ftp ftp-client

将base64String保存为FTP服务器上的图像将其保存为损坏的文件。 我正在做一些事情

  1. 将base64String转换为byte []。
  2. 在上一步中转换了字节的初始化MemoryStream。
  3. 从FTP打开流
  4. 在ftp上写流。
  5. 以下是代码

    public bool WriteFromBase64ToFile(string base64, string path, string fileName)
        {
            bool result = false;
    
            using (FtpClient ftp = new FtpClient())
            {
    
                // setting ftp properties with required values.
                ftp.ReadTimeout = 999999999;
                ftp.Host = host;
                ftp.Credentials = new System.Net.NetworkCredential(username, password);
                ftp.Port = Convert.ToInt32(port);
                ftp.DataConnectionType = FtpDataConnectionType.AutoPassive;
                ftp.Connect();
                ftp.ConnectTimeout = 1000000;
    
                // converting base64String into byte array.
                byte[] file = Convert.FromBase64String(base64);
    
    
    
                if (ftp.IsConnected)
                {
                    int BUFFER_SIZE = file.Length; // 64KB buffer
                    byte[] buffer = new byte[file.Length];
    
                    // Initializing MemoryStream with byte converted from base64String.
                    MemoryStream ms = new MemoryStream(buffer);
    
                    using (Stream readStream = ms)
                    {
                        fileName = fileName.ReplacingSpecialCharacterswithEntities();
    
                        // Getting stream from ftp and then writing it on FTP server.
                        using (Stream writeStream = ftp.OpenWrite(path + "/" + fileName+".jpg", FtpDataType.Binary))
                        {
    
                            while (readStream.Position < readStream.Length)
                            {
                                buffer.Initialize();
    
                                // Reading stream
                                int bytesRead = readStream.Read(buffer, 0, BUFFER_SIZE);
                                // Writing stream
                                writeStream.Write(buffer, 0, bytesRead);
                            }
    
                            // flushing stream.
                            writeStream.Flush();
                        }
                    }
                }
            }
            result = true;
            return result;
        }
    

0 个答案:

没有答案