无法上传带有chrome和ftpwebrequest的文件

时间:2015-08-06 13:00:01

标签: c# asp.net-mvc

我在我的MVC 5应用程序中实现功能(使用ftpWebRequest类)让用户通过表单选择文件,然后将其上传到ftp服务器。在IE中它可以正常工作但是当我切换到chrome / firefox / safari时我会卡住,因为这些浏览器使用类似 c:\ fakepath \ examplefile.png 的东西 有没有办法使用chrome / firefox / safari上传文件?

HTML

<form id="frmUpload" enctype="multipart/form-data">
    <input type="file" name="fileN" id="file" />
</form>
<button id="btnUploadx">Upload</button>

脚本

$("#btnUploadx").on("click", function () {
    uploadFile();            
});

function uploadFile() {

    var formData = new FormData($('#frmUpload')[0]);

    ajax = new XMLHttpRequest();
    //ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.open("POST", "@urlPath/Ftp/AjaxUploadFile/");
    ajax.send(formData);
 }

操作AjaxUploadFile

[HttpPost]
public ActionResult AjaxUploadFile(HttpPostedFileBase fileN, string folder)
{
    Dictionary<string, string> strMsg = new Dictionary<string, string>();
    completePath = System.IO.Path.
                       GetFullPath(Request.Files["fileN"].FileName);
    fileName = System.IO.Path.GetFileName(completePath);

    string strFtp = "ftp://" + serverIp + "/folder/" + fileName;

        try
        {

            FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(strFtp);
            ftpReq.UseBinary = true;
            ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
            ftpReq.Credentials = new NetworkCredential(userName, password);

            ftpReq.ContentLength = fileN.ContentLength;

            byte[] b = System.IO.File.ReadAllBytes(completePath);
            ftpReq.ContentLength = b.Length;

            using (Stream s = ftpReq.GetRequestStream())
            {
                s.Write(b, 0, b.Length);
            }

            FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

            return RedirectToAction("Details", "OrderLine", new { id = folder });
        }
        catch (Exception ex)
        {

            return RedirectToAction("Details", "OrderLine", new { id = folder });
        }


    }

1 个答案:

答案 0 :(得分:0)

在做了一些测试后,我找到了改变控制器/动作中byte []部分的解决方案。我不得不改变:

byte[] b = System.IO.File.ReadAllBytes(completePath);
ftpReq.ContentLength = b.Length;

byte[] b = null;
using (var binaryReader = new BinaryReader(Request.Files["fileN"].InputStream))
{
    b = binaryReader.ReadBytes(Request.Files["fileN"].ContentLength);
}