在我的应用程序中,我到目前为止已设法将图像上传到服务器。现在我想在ASP.NET MVC5中使用javascript动态设置上传的图像作为背景。这是我的代码。此部分从本地存储中读取文件
jQuery(document).ready(function ()
{
jQuery("#imageBrowes").change(function ()
{
var File = this.files;
if (File && File[0])
{
ReadImage(File[0]);
}
})
})
var ReadImage = function(file)
{
var reader = new FileReader;
var image = new Image;
reader.readAsDataURL(file);
reader.onload = function(_file)
{
image.src = _file.target.result;
image.onload = function()
{
var height = this.height;
var width = this.width;
var type = file.type;
var size = ~~(file.size / 1024) + "KB";
jQuery("#targetImg").attr('src', _file.target.result);
jQuery("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
jQuery("#imgPreview").show();
}
}
}
此部分将图像存储到文件服务器系统中:
var ClearPreview = function(){
jQuery("#imageBrowes").val('');
jQuery("#description").text('');
jQuery("#imgPreview").hide();
}
var Uploadimage = function()
{
var file = jQuery("#imageBrowes").get(0).files;
var data = new FormData;
data.append("ImageFile", file[0]);
jQuery.ajax({
type: "Post",
url: "/Home/ImageUpload",
data: data,
contentType: false,
processData: false,
success: function (response) {
ClearPreview();
jQuery("#uploadedImage").append('<img src="/elements-images/' + response + '" class="img-responsive thumbnail"/>');
}
})
}
这是在上面的javascript中调用的动作:
public ActionResult ImageUpload(ProductViewModel model)
{
var file = model.ImageFile;
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var extention = Path.GetExtension(file.FileName);
var filenamewithoutextension = Path.GetFileNameWithoutExtension(file.FileName);
file.SaveAs(Server.MapPath("/elements-images/" + file.FileName));
}
return Json(file.FileName, JsonRequestBehavior.AllowGet);
}
所以基本上图像文件保存在elements-images文件夹中。如何将该文件夹中的特定图像设置为背景图像?
答案 0 :(得分:0)
Javascript侧预览
对于文件的javascript侧预览,请更改此行
jQuery("#targetImg").attr('src', _file.target.result);
到
jQuery("#targetImg").attr('src', "data:" + file.type + ";base64," + btoa(_file.target.result) );
在服务器上传后预览
要在服务器响应后显示图像,您的代码似乎是正确的。您似乎需要在操作结果中更改此行
return Json(file.FileName, JsonRequestBehavior.AllowGet);
所以它看起来像这样
public ActionResult ImageUpload(ProductViewModel model)
{
var file = model.ImageFile;
string fileName = string.Empty;
if (file != null)
{
fileName = Path.GetFileName(file.FileName);
var extention = Path.GetExtension(file.FileName);
var filenamewithoutextension = Path.GetFileNameWithoutExtension(file.FileName);
file.SaveAs(Server.MapPath("/elements-images/" + file.FileName));
}
return Json(fileName, JsonRequestBehavior.AllowGet);
}