繁体   English   中英

将发布的文件上传到FTP会在ASP.NET中将其损坏

[英]Uploading a posted file to FTP corrupts it in ASP.NET

成功上传图片HTTP。 加载之前,我正在使用JavaScript进行预览。

加载图像后,图像将转换为黑色。 StreamReader可能有问题吗?

可以看到,我想念什么? 谢谢..

asp.net

<input id="fileupload2" type="file" runat="server" clientidmode="Static" />

代码隐藏

string fileName = Path.GetFileName(fileupload2.PostedFile.FileName);
using (StreamReader fileStream = new StreamReader(fileupload2.PostedFile.InputStream))
{
    fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());                
    fileStream.Close();
}

try
{
    if (fileupload2.PostedFile.ContentLength < 5120000)
    {
        //Create FTP Request.
        FtpWebRequest request =
            (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        //Enter FTP Server credentials.
        request.Credentials = new NetworkCredential("USER", "PASS");
        request.ContentLength = fileBytes.Length;
        request.UsePassive = true;
        request.UseBinary = true;
        request.ServicePoint.ConnectionLimit = fileBytes.Length;
        request.EnableSsl = false;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileBytes, 0, fileBytes.Length);
            requestStream.Close();
        }

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        //   lblMessage.Text += fileName + " uploaded.<br />";
        response.Close();
    }
    else
    {
        ScriptManager.RegisterClientScriptBlock(
            this, this.GetType(), "Dikkat",
            "alert('Dosya 5 MB'dan küçük olmalıdır.')", true);
    }
}
catch (WebException ex)
{
    throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}

我怀疑这也归因于StreamReader StreamReader专用于文本,而不仅仅是byte[]

相反,我将仅使用FileUpload.FileBytes来检索数据,而不是FileUpload.PostedFile.InputStream 或者,您可以使用Stream.Read()来处理更通用的数据流。

 fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd()); 

您尝试将二进制文件解释为UTF-8文本。 那根本行不通。

此外,由于不必要地将整个文件复制到内存中,因此实现效率很低。


这是一个简单而有效的解决方案:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("USER", "PASS");

using (Stream requestStream = request.GetRequestStream())
{
    fileupload2.PostedFile.InputStream.CopyTo(requestStream);
}

不需要其他代码:

  • UsePassive = trueUseBinary = trueEnableSsl = false是默认设置。
  • FtpWebRequest未使用ContentLength
  • 上传不需要FtpWebRequest.GetResponse调用。
  • ServicePoint.ConnectionLimit与字节数无关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM