[英]How to upload large files to FTP server in ASP MVC
I am developing an ASP MVC website. 我正在开发一个ASP MVC网站。 Now i need to upload files(.zip files) to my FTP server.
现在,我需要将文件(.zip文件)上传到我的FTP服务器。 For uploading i use this code.
对于上传,我使用此代码。
This code uploads only those files which has size < 10 Mb. 此代码仅上传大小小于10 Mb的文件。
for Example: when i upload a file with 150 MB size with this code it get damaged and the file size changed to 300 MB on my Ftp Server. 例如:当我用此代码上传文件大小为150 MB时,文件被损坏,文件传输服务器上的文件大小更改为300 MB。
So can any one help me.. 所以任何人都可以帮助我..
byte[] fileBytes = null;
//Read the FileName and convert it to Byte array.
string filename = Path.GetFileName(FileUpload1.FileName);
using (StreamReader fileStream = new StreamReader(FileUpload1.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + "/" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
//Enter FTP Server credentials.
request.Credentials = new NetworkCredential(ftpUName, ftpPWord);
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();
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
Add this to your web.config 将此添加到您的web.config
<httpRuntime maxRequestLength="whatever value you need in kb max value is 2,147,483,647 kb" relaxedUrlToFileSystemMapping="true" />
under system.web section the default is 4 mb size limit 在system.web部分下,默认值为4 mb
It probably gets corrupt, because you are reading the data with utf8 encoded. 它可能已损坏,因为您正在读取utf8编码的数据。 You should read it in binary format.
您应该以二进制格式阅读它。
Don't use: 不要使用:
using (StreamReader fileStream = new StreamReader(FileUpload1.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
You have to use File.ReadAllBytes or a BinaryReader (Stream) 您必须使用File.ReadAllBytes或BinaryReader (流)
https://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/system.io.file.readallbytes(v=vs.110).aspx
https://msdn.microsoft.com/de-de/library/system.io.binaryreader(v=vs.110).aspx https://msdn.microsoft.com/de-de/library/system.io.binaryreader(v=vs.110).aspx
for your example: 例如:
byte[] fileBytes = File.ReadAllBytes(Path.GetFileName(FileUpload1.FileName));
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.