成功的图片HTTP上传。我在加载前使用JavaScript进行预览。
图片加载时图片会变黑。
这可能是StreamReader
的问题吗?
<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);
}
答案 0 :(得分:1)
我怀疑这也归因于StreamReader
。 StreamReader专门用于文本,而不仅仅是任何byte[]
。
相反,我只需使用FileUpload.FileBytes
来检索数据而不是FileUpload.PostedFile.InputStream
。或者您可以使用Stream.Read()
来表示更通用的数据流。
答案 1 :(得分:1)
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); }
您尝试将二进制文件解释为UTF-8文本。那是行不通的。
此外,由于您不必要地将整个文件复制到内存中,因此您的实现效率非常低。
这是一个简单而有效的解决方案:
UsePassive = true
不需要其他代码:
UseBinary = true
,EnableSsl = false
和ContentLength
是默认设置。FtpWebRequest
未在FtpWebRequest.GetResponse
。中使用
上传不需要ServicePoint.ConnectionLimit
来电。if (nums.length = 0) {
return -1;
}
与字节数无关。