C# 4.0 如何使用ajax或任何其他技术在ASP.NET MVC 4中上载图像而无需回发?
我正在用MVC4开发一个网站,在那里用户填写一些信息并保存以上传。 除图像外的所有信息都使用Javascript、Json和Ajax保存在服务器上,如下所示:C# 4.0 如何使用ajax或任何其他技术在ASP.NET MVC 4中上载图像而无需回发?,c#-4.0,file-upload,asp.net-mvc-4,C# 4.0,File Upload,Asp.net Mvc 4,我正在用MVC4开发一个网站,在那里用户填写一些信息并保存以上传。 除图像外的所有信息都使用Javascript、Json和Ajax保存在服务器上,如下所示: $.ajax({ url: action, type: "POST", data: JSON.stringify(PostViewModel), dataType: "json",
$.ajax({
url: action,
type: "POST",
data: JSON.stringify(PostViewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
},
success: function (data) {
try{
alert('success');
}catch(err){alert(' Error: '+err);}
},
complete: function () {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error occured");
}
});
HttpPostedFileBase photo = Request.Files["photo"];
if (photo != null)
{
Session["ImgPath"] = "~/Content/PostImages/" + photo.FileName;
string path = Server.MapPath("~/Content/PostImages/");
photo.SaveAs(path + photo.FileName);
}
但现在我也需要上传他的照片,但我找不到任何方法可以使用这种方法,也找不到任何没有回复的方法
我知道将FileUpload控件放在表单标签中,按下submit按钮,我可以得到如下所示的图像文件:
$.ajax({
url: action,
type: "POST",
data: JSON.stringify(PostViewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
},
success: function (data) {
try{
alert('success');
}catch(err){alert(' Error: '+err);}
},
complete: function () {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error occured");
}
});
HttpPostedFileBase photo = Request.Files["photo"];
if (photo != null)
{
Session["ImgPath"] = "~/Content/PostImages/" + photo.FileName;
string path = Server.MapPath("~/Content/PostImages/");
photo.SaveAs(path + photo.FileName);
}
但是对于这种方法,我必须改变我保存内容的方法(使用Javascript、Json和Ajax),我不能这样做
请帮忙
谢谢。异步发布文件(图像)有两种方法 如果目标浏览器支持文件api,则可以使用以下内容: HTML:
或者你可以使用swf工具,比如我个人不喜欢使用java脚本、css或html以外的任何第三方工具。我将使用UmairP展示的第一种方法。但是,如果您想节省自己的时间来编写大部分代码。下面是jquery的一个不错的例子 还有一个用于asp.net mvc的插件
请看一看。如果需要进一步的信息,请告诉我 我也遇到了类似的问题,在被困了很多天后,这个链接终于帮助了我 我就是这样做的
public JsonResult Upload(HttpPostedFileBase file)
{
if (Session["myAL"] == null)
{
al = new ArrayList();
}
else
al = (ArrayList)Session["myAL"];
var uploadFile = file;
if (uploadFile != null && uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Uploads"),
Path.GetFileName(uploadFile.FileName));
al.Add(filePath);
Session["myAL"] = al;
uploadFile.SaveAs(filePath);
}
var percentage = default(float);
if (_totalCount > 0)
{
_uploadCount += 1;
percentage = (_uploadCount / _totalCount) * 100;
}
return Json(new
{
Percentage = percentage
});
}
试试这个它对我有用
<input type="file" name="Upload" id="Upload" />
$('#Upload').change(function () {
debugger;
var file = document.getElementById('Upload').files[0];
var fileName = file.name;
var fd = new FormData();
fd.append("fileData", file);
fd.append("key", '@Model.Id');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
xhr.open("POST", "/ImageHandler.ashx", true);
xhr.send(fd);
});
function UploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
//$("#uploading").text(percentComplete + "% ");
}
}
function UploadComplete(evt) {
//if (evt.target.status == 200)
//alert(evt.target.responseText);
//else {
// // alert("Error Uploading File");
//}
}
function UploadFailed(evt) {
// alert("There was an error attempting to upload the file.");
}
function UploadCanceled(evt) {
//alert("The upload has been canceled by the user or the browser dropped the connection.");
}
$('#Upload')。更改(函数(){
调试器;
var file=document.getElementById('Upload')。文件[0];
var fileName=file.name;
var fd=新FormData();
fd.append(“文件数据”,文件);
append(“key”,“@Model.Id”);
var xhr=new XMLHttpRequest();
addEventListener(“progress”,函数(evt){UploadProgress(evt);},false);
addEventListener(“加载”,函数(evt){UploadComplete(evt);},false);
addEventListener(“错误”,函数(evt){UploadFailed(evt);},false);
addEventListener(“中止”,函数(evt){UploadCanceled(evt);},false);
open(“POST”,“/ImageHandler.ashx”,true);
xhr.send(fd);
});
函数上载进度(evt){
if(evt.长度可计算){
var percentComplete=数学整轮(evt.loaded*100/evt.total);
//$(“#上传”).text(完成百分比+“%”);
}
}
功能上传完成(evt){
//如果(evt.target.status==200)
//警报(evt.target.responseText);
//否则{
////警报(“上传文件时出错”);
//}
}
函数上载失败(evt){
//警报(“尝试上载文件时出错。”);
}
功能上载已取消(evt){
//警报(“用户已取消上载或浏览器已断开连接”);
}
处理程序:
公共类ImageHandler:IHttpHandler
{
公共void ProcessRequest(HttpContext上下文)
{
//context.Response.ContentType=“text/plain”;
//context.Response.Write(“Hello World”);]
字符串filePath=Constants.ImageFolderPath;
//在这里编写处理程序实现。
if(context.Request.Files.CountHTML代码
<input type="file" id="uploadEditorImage" />
MVC控制器中的代码
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
如果(file!=null&&file.ContentLength>0)
{
字符串文件名=Path.GetFileName(file.filename);
字符串imgpath=Path.Combine(Server.MapPath(“~/Img/”),文件名);
file.SaveAs(imgpath);
student.photo=imgpath;
}
函数readURL(输入)
{
if(input.files&&input.files[0]){
var reader=new FileReader();
reader.onload=函数(e){
$(“#imgUser”)
.attr('src',e.target.result)
.宽度(150)
.身高(200);
};
reader.readAsDataURL(input.files[0]);
}
}
谢谢你发布这篇文章!今天我来看了这篇文章,一切都很好,但是UploadProgress有一个jquery,它给javascript增加了一点痛苦:-)应该向控制器操作传递什么参数?我应该使用@if(System.Web.HttpContext.Current.Request.Files.AllKeys.Any()){var pic=System.Web.HttpContext.Current.Request.Files[“HelpSectionImages”];pic.SaveAs(“/”+pic.FileName);}
?我在想-为什么Ajax.BeginForm在这里不起作用,但是纯JS ist:)仍然-很好的回答请添加一些解释
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
});
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
$(document).ready(function(){
var status = $('#status');
$('#frmUpload').ajaxForm({
beforeSend: function () {
if ($("#file").val() != "") {
$("#progressDiv").show();
}
status.empty();
},
success: function () {
showTemplateManager();
},
complete: function (xhr) {
if ($("#file").val() != "") {
var millisecondsToWait = 500;
setTimeout(function () {
$("#progressDiv").hide();
}, millisecondsToWait);
}
status.html(xhr.responseText);
}
});
});
<input type="file" name="file" id="file" style="width: 100%;"onchange="readURL(this);" />
if (file != null && file.ContentLength > 0)
{
string filename = Path.GetFileName(file.FileName);
string imgpath = Path.Combine(Server.MapPath("~/Img/"), filename);
file.SaveAs(imgpath);
student.photo = imgpath;
}
function readURL(input)
{
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgUser')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}