我可以从ASP.NET MVC中的ajax XHR请求保存文件吗?

时间:2011-05-27 04:55:05

标签: c# asp.net-mvc

我在jQuery中使用ajaxSubmit来预览图像,但我真的可以保存这些图像。

如果是,那么有人可以告诉我代码吗?

2 个答案:

答案 0 :(得分:2)

如果您的浏览器支持HTML5中的FileReader API,则可以执行此操作。

您需要做的基本事情是:

    xhr.open("POST", url);    
    xhr.setRequestHeader("Content-Type", "multipart/form-data,);
    xhr.setRequestHeader("Cache-Control", "no-cache");     
    body += "Content-Type: application/octet-stream\r\n\r\n";
    body += reader.result + "\r\n"; 
    if(xhr.sendAsBinary) {
      // only firefox
      xhr.sendAsBinary(body);
    } else {
      // chrome (as in W3C)
      xhr.send(body);
    }
  };
  //reading file
  reader.readAsBinaryString(file);

代码可能不是100%正确,但你明白了。 您的浏览器应支持FileReader API,您可以在html5test.com

上查看

希望这有帮助。

答案 1 :(得分:0)

考虑使用此js library进行客户端上传。服务器端代码可能如下所示:

var destination = Path.GetTempFileName(); // you should probably replace this with a directory the IIS Worker Process has write permission to
try {
    Request.Files[0].SaveAs(destination);
    // Save destination to database or wherever
} finally {
    File.Delete(destination);
}