【问题标题】:How do I set Filestream from an fileupload control?如何从文件上传控件设置文件流?
【发布时间】:2011-10-27 20:25:55
【问题描述】:

这是我的代码,我似乎无法将 FileUploadCotrol 中的文件放入 FILESTREAM。

 // The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();

try
{
    // Stream to which the file to be upload is written
    Stream strm = reqFTP.GetRequestStream();

    // Read from the file stream 2kb at a time
    contentLen = fs.Read(buff, 0, buffLength);

    // Till Stream content ends
    while (contentLen != 0)
    {
        // Write Content from the file stream to the FTP Upload Stream
        strm.Write(buff, 0, contentLen);
        contentLen = fs.Read(buff, 0, buffLength);
    }

    // Close the file stream and the Request Stream
    strm.Close();
    fs.Close();
}

似乎我应该使用 Fileupload 控件从我的网站执行此操作,但奇怪的是控件创建的是流而不是文件流。是的,我正在通过 FTP 传输文件。

【问题讨论】:

  • 'fileInf' 是什么类型? 'reqFTP' 是什么类型?
  • 我认为最终您将需要使用 MemoryStream。但需要更多信息
  • FileInfo fileInf = new FileInfo(filename); br> FtpWebRequest reqFTP; br> // 从提供的 Uri 创建 FtpWebRequest 对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(" ftp://" + sFtpId + "/" + fileInf.Name)) 我传入了从文件上传控件获得的文件名。
  • 哇,今天早上还没有。我可能不得不采用 Microsoft 的两步方法,将控件放在服务器上,然后从那里 FTP? Yuk,我得打电话给 ISP,看看我是否有空间存放大文件。
  • 好吧,目前做两步过程还需要用100mg的文件进行测试。

标签: asp.net visual-studio-2010 c#-4.0 asp.net-4.0


【解决方案1】:

这是一个示例方法,它将我们所针对的两种类型 FileInfoFtpWebRequest 作为参数并在它们之间传输数据。我相信这会奏效。

    void UploadFileToFtp(FileInfo file, FtpWebRequest req)
    {
        int buffLength = 2048;

        using (var reader = new BinaryReader(file.OpenRead()))
        {
            using (var writer = new BinaryWriter(req.GetRequestStream()))
            {
                while (reader.PeekChar() > 0) writer.Write(reader.ReadBytes(buffLength));
            }
        }
    }

希望这会有所帮助!

【讨论】:

  • 我会试一试,我确实让它在两步过程中工作,但我真的很想避免在那里存储这种大小的任何东西。
  • 出现错误 ---- 输出字符缓冲区太小,无法包含解码字符,编码为 'Unicode (UTF-8)' fallback 'System.Text.DecoderReplacementFallback'。参数名称:chars 把文件放到ftp服务器上,但是已经损坏了。
  • 我可以通过添加打开的“,Encoding.ASCII”来消除错误。但是我正在加载的 pdf 文件仍然是垃圾。
  • 服务器上的文件大小为 82KB,PDF 应为 613.6 KB
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2015-10-02
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多