[英]Upload file to virtual directory using Ajax call
我正在将CMS作为MVC 4项目构建,其功能之一就是上传照片 。 用户从他的硬盘驱动器中选择一张照片,这会触发对控制器上UploadFile方法的ajax请求。 这会将照片复制到服务器上的虚拟文件夹中。 问题是我不太了解浏览器将文件存储在何处并将其发送到服务器,以及我在控制器上应该执行的操作。
到目前为止,这是我的代码-
风景:
<input id="cng_pic_btn" type="file" name="file" accept="image/*" /></td>
JavaScript调用服务器:
$('#cng_pic_btn').live('change', function () {
custom_url = "/SideBar/UploadFile";
return_msg = "file uploaded";
var file_path = $('#cng_pic_btn').attr("value");
alert(file_path);
sendInfo = {
upload_from: file_path
}
CreataAjaxRequest(custom_url, sendInfo, return_msg);
})
控制器方法:
[HttpPost]
public void UploadFile(string upload_from)
{
string path = @"D:\Temp\";
HttpPostedFileBase photo = Request.Files[upload_from];
photo.SaveAs(path + photo.FileName);
}
发送ajax请求:
function CreataAjaxRequest(custom_url, sendInfo, return_msg) {
$.ajax({ type: "POST", url: custom_url, data: sendInfo })
.success(function (html) {
$(".query-result").replaceWith(html);
})
}
您尚未显示CreataAjaxRequest
方法,但如果要使用AJAX上传文件,则有两个选项:
HTML 5 File API
在这种情况下,您可以使用XmlHttpRequest2对象 Uploadify
或Fine Uploader
),这些插件对这类旧版浏览器使用隐藏的iframe或Flash电影等技术。 以下是使用HTML 5 File API上传文件的示例:
function CreataAjaxRequest(custom_url, sendInfo, return_msg) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', custom_url, true);
var file = document.getElementById('cng_pic_btn').files[0];;
fd.append('myFile', file);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
$('.query-result').replaceWith(xhr.responseText);
}
};
xhr.send(fd);
}
然后在您的服务器上:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase myFile)
{
var path = string path = @"D:\Temp\";
myFile.SaveAs(Path.Combine(path, myFile.FileName));
return PartialView();
}
另请注意,如果您想使用$('.query-result').replaceWith(xhr.responseText);
则控制器操作需要返回PartialView
$('.query-result').replaceWith(xhr.responseText);
AJAX回调中的方法,否则将替换为什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.