mvc视图中怎么上传图片并显示
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mvc视图中怎么上传图片并显示相关的知识,希望对你有一定的参考价值。
如果只是上传的话那太容易了,如果还要显示那就难了,因为要显示的话就不能只向服务器提交一次请求,必须异步提交。下面的例子是我亲自写的,异步提交上传图片并预览。全部代码都在。
首先建一个html文件,复制以下html文本。使用说明:
引用jquery两个js文件,网上自己搜吧,到处都有。
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
2.添加两个文本框,第一个ID必须是“bigImage1”,第二个必须是“smallbigImage1”。
<input type="text" name="url1" id="bigImage1" style="width:150px;" onclick="selectImage(this)" />
<input type="hidden" name="smallUrl1" id="smallbigImage1" value="" />
当点击第一个文本框时,弹出一个上传窗口,选择一张图片并点“上传”,上传成功后可预览图片。此过程会在服务器上把原图片生成一张缩略图,并把原图URL和缩略图URL一起以JSON格式返回到前台页面,临时显示缩略图。当点击“确定”时,它会把两个URL添加到两个对应ID的文本框。第二个框是隐藏的,给用户的感觉就像是只返回一个URL一样。
3.请自己写脚本[document.getElementById("bigImage1").value] 获得两个文本框的值,再进行你想做的操作。
4.id为"uploadDiv"的DIV是一个整体,不可分割。主要是提供一个文件类型的表单,用于异步上传。请修改action的URL为你上传的后台路径。
下面是HTML代码
<!DOCTYPE html><html>
<head>
<title>Index</title>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
function selectImage(obj)
var inputId = obj.id;
document.getElementById(\'btnSure\').setAttribute(\'inputId\', inputId);
var x = window.event.x;
var y = window.event.y;
var uploadDiv = document.getElementById(\'uploadDiv\');
uploadDiv.style.left = x + 10 + \'px\';
uploadDiv.style.top = y + 10 + \'px\';
uploadDiv.style.position = \'fixed\';
uploadDiv.style.display = \'inline\';
function closeDiv()
document.getElementById(\'btnSure\').style.display = \'none\';
document.getElementById(\'showImage\').style.display = \'none\';
document.getElementById(\'uploadDiv\').style.display = \'none\';
function makeSure(obj)
var inputId = obj.getAttribute(\'inputId\');
document.getElementById(inputId).value = document.getElementById(\'showImage\').getAttribute(\'big\');
document.getElementById(\'small\' + inputId).value = document.getElementById(\'showImage\').getAttribute(\'small\');
document.getElementById(\'image\' + inputId).src = document.getElementById(\'showImage\').getAttribute(\'small\');
document.getElementById("btnSure").style.display = \'none\';
document.getElementById(\'showImage\').style.display = \'none\';
document.getElementById(\'uploadDiv\').style.display = \'none\';
$(function ()
//异步上传图片
$(\'#btnUpload\').click(function ()
if ($(\'#upImage\').val() == \'\')
alert(\'请选择一张图片文件\');
return;
$(\'#fileForm\').ajaxSubmit(
success: function (msg)
var strJSON = msg; //得到的JSON
var image = eval("(" + strJSON + ")"); //转换后的JSON对象
document.getElementById(\'uploading\').style.display = \'none\';
$(\'#showImage\').css(\'display\', \'inline\');
$(\'#showImage\').attr(\'src\', image.big);
$(\'#showImage\').attr(\'big\', image.big);
$(\'#showImage\').attr(\'small\', image.small);
$(\'#btnSure\').css(\'display\', \'inline\');
);
document.getElementById(\'uploading\').style.display = \'block\';
);
);
</script>
</head>
<body>
<p>上传单个文件或图片</p>
<div>
<input type="text" name="url1" id="bigImage1" style="width:150px;" onclick="selectImage(this)" />
<input type="hidden" name="smallUrl1" id="smallbigImage1" value="" />
</div>
<div id="uploadDiv" style="width: 400px; height: 280px; border: 1px solid #9eb9f1;
background-color: #e1eaea; text-align:left; display:none; z-index:999;">
<div>
<div style="width: 376px; float: left; padding-left:4px; padding-top:4px; padding-bottom:4px; overflow:hidden;">
<form id="fileForm" method="post" action="/Home/UploadImage" enctype="multipart/form-data" >
<input type="file" id="upImage" name="upImage" style="padding-bottom: 1px; padding-left: 8px;
padding-right: 8px; height: 24px; width:220px; padding-top: 1px;" />
<input type="button" id="btnUpload" value="上传" style="padding-bottom: 1px; padding-left: 8px; padding-right: 8px;
height: 24px; cursor: pointer; padding-top: 1px; line-height: 12px;" />
<span id="uploading" style="color:#ff0000; display:none; font-size:14px; font-weight:bold;">上传中......</span>
<input type="button" id="btnSure" value="确定" style="padding-bottom: 1px; padding-left: 8px; padding-right: 8px;
height: 24px; cursor: pointer; padding-top: 1px; line-height: 12px; display:none; background-color:#9fd0f9;" onclick="makeSure(this)" />
</form>
</div>
<div style="width: 20px; height: 30px; float: right; ">
<div style="width: 20px; height: 20px; background-color:#9fc0f7; font-size:20px; text-align:center; line-height:16px; cursor:pointer;" onclick="closeDiv()">X</div>
</div>
</div>
<div style="width:398px; height:240px; text-align:center; overflow:hidden; ">
<img id="showImage" src="" style="width: 340px; display:none;" />
</div>
</div>
</body>
</html>
下面是后台代码
返回到前台页面的JSON格式对象是以类的对象。public class ReturnImage
public string big get; set;
public string small get; set;
public string isSuccessfull get; set;
public string message get; set;
对于上传和生成缩略图,请自行完成,以下是ASP.NET MVC的例子。
public class HomeController : Controller
//
// GET: /Home/
public ActionResult Index()
return View();
/// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
public ActionResult UploadImage()
//定义错误消息
JsonResult msg = new JsonResult();
try
//接受上传文件
HttpPostedFileBase postFile = Request.Files["upImage"];
if (postFile != null)
DateTime time = DateTime.Now;
//获取上传目录 转换为物理路径
string uploadPath = Server.MapPath("~/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/");
//文件名
string fileName = time.ToString("yyyyMMddHHmmssfff");
//后缀名称
string filetrype = System.IO.Path.GetExtension(postFile.FileName);
//获取文件大小
long contentLength = postFile.ContentLength;
//文件不能大于2M
if (contentLength <= 1024 * 2048)
//如果不存在path目录
if (!Directory.Exists(uploadPath))
//那么就创建它
Directory.CreateDirectory(uploadPath);
//保存文件的物理路径
string saveFile = uploadPath + fileName + "_big" + filetrype;
try
//保存文件
postFile.SaveAs(saveFile);
//保存缩略图的物理路径
string small = uploadPath + fileName + "_small" + filetrype;
MakeThumbnail(saveFile, small, 320, 240, "W");
ReturnImage image = new ReturnImage();
image.big = "/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/" + fileName + "_big" + filetrype;
image.small = "/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/" + fileName + "_small" + filetrype;
msg = Json(image);
catch
msg = Json("上传失败");
else
msg = Json("文件大小超过限制要求");
else
msg = Json("请选择文件");
catch (Exception e)
;
msg.ContentType = "text/html";
return msg;
/// <summary>
由于回答超过最大限制,/// 生成缩略图 的代码请向我索取 参考技术A 通过form post提交 参考技术B html 拉控件到mvc
<style>
#delimg
width: 25px;
height: 25px;
margin-left: 30px;
</style>
<div>
<textarea id="txtcon"></textarea>
</div>
<div id="uploader-demo">
<!--用来存放item-->
<div id="fileList" class="uploader-list"></div>
<div id="filePicker" style="float:left">选择图片</div>
<div style="float:left">
<button id="ctlBtn" style="background-color: #FF5722; height: 41px; line-height: 41px; padding: 0 18px; color: #fff; white-space: nowrap; text-align: center; font-size: 14px; border: none; border-radius: 2px; cursor: pointer; ">
开始上传
</button>
</div>
<div>
<input type="text" id="hidfilenames" />
</div>
</div>
<div>
<input type="hidden" id="hiduserid" value="1" />
<input type="button" value="提交" onclick="save()" />
</div>
<script type="text/javascript">
$(document).ready(function ()
//开始上传
$("#ctlBtn").click(function ()
uploader.upload();
);
var uploader = WebUploader.create(
// 选完文件后,是否自动上传。
auto: false,
// swf文件路径
swf: '"~/Scripts/myJs/Uploader.swf"',//这个地方换成自己文件存放的路径
// 文件接收服务端。
server: '/Default/UpLoadProcess', //控制器动作路径
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
// 只允许选择图片文件。
accept:
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
);
var $list = $("#fileList");
var thumbnailWidth = "100";
var thumbnailHeight = "100";
uploader.on('fileQueued', function (file)
var $li = $(
'<div style="display:inline-block;margin-left:10px" id="' + file.id + '" class="file-item thumbnail">' +
'<img>'
),
$img = $li.find('img[id!=delimg]');
// $list为容器jQuery实例
$list.append($li);
// 创建缩略图
// 如果为非图片文件,可以不用调用此方法。
// thumbnailWidth x thumbnailHeight 为 100 x 100
uploader.makeThumb(file, function (error, src)
if (error)
$img.replaceWith('<span>不能预览</span>');
return;
$img.attr('src', src);
, thumbnailWidth, thumbnailHeight);
);
//删除预览图片
$list.on("click", "#delimg", function ()
var ID = $(this).parent().attr('id');
var quID = uploader.getFile(ID);
uploader.removeFile(quID);
$(this).parent().remove();
)
uploader.on('uploadSuccess', function (file, response)
var v = $("#hidfilenames").val();
$("#hidfilenames").val(v + ',' + response.filePath);
);
uploader.on('uploadFinished', function (file, response)
//所有图片上传成功回调函数
alert("上传成功");
$(".delimg").hide();
);
uploader.on('uploadError', function (file)
//文件上传失败,显示上传出错。
);
)
function save()
$.ajax(
url: "http://localhost:50748/api/Default/Proc",
type: "get",
data: id: location.href.split("=")[1], yy: $("#txtcon").val(), tp: $("#hidfilenames").val() ,
dataType: "json",
success: function (d)
if (d > 0)
alert("成功");
else alert("失败");
)
namespace qwe
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
public void ProcessRequest(HttpContext context)
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
HttpPostedFile file = context.Request.Files["files"];
string uploadPath = HttpContext.Current.Server.MapPath("../Img/") + "\\";
if (file != null)
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
file.SaveAs(uploadPath + file.FileName);
//下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
string newName = file.FileName;
string oldName = file.FileName;
context.Response.Write("\"newName\": \"" + newName + "\", \"oldName\": \"" + oldName + "\"");
else
context.Response.Write("0");
public bool IsReusable
get
return false;
控制器
public ActionResult UpLoadProcess(string id, HttpPostedFileBase file)
string filePathName = string.Empty;
string localPath = "../Img/";
if (Request.Files.Count == 0)
return Json(new jsonrpc = 2.0, error = new code = 102, message = "保存失败" );
file.SaveAs(Server.MapPath(localPath + file.FileName));
return Json(new
jsonrpc = "2.0",
id = id,
filePath = "/Img/" + file.FileName
);
参考技术C <script type="text/javascript">
//图片预览
$("#imgfile").uploadPreview(
imgDiv: "#imgDiv",
imgType: ["bmp", "gif", "png", "jpg"],
maxwidth: 250,
maxheight: 250
);
//上传图片
$("#btnUpload").click(function()
$.post("Controllers/UploadFile.ashx", upfile: getPath($("#imgfile")) , function (json)
//json.result为upload.ashx文件返回的值
alert(json.result);
,"json");
);
);
</script>
[code=HTML]
<input id="imgfile" type="file" />
<input type="button" id="btnUpload" value="上传图片" />
<div id="imgDiv" runat="server"></div> //显示预览图片 参考技术D @
ViewBag.Title = "Index";
<link href="~/Scripts/webuploader/webuploader.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/webuploader/webuploader.js"></script>
<style>
#delimg
width: 25px;
height: 25px;
margin-left: 30px;
</style>
<input type="hidden" id="pid" value="@ViewBag.Pid" />
<div>
<textarea id="txtcon"></textarea>
</div>
<div id="uploader-demo">
<!--用来存放item-->
<div id="fileList" class="uploader-list"></div>
<div id="filePicker" style="float:left">选择图片</div>
<div style="float:left">
<button id="ctlBtn" style="background-color: #FF5722; height: 41px; line-height: 41px; padding: 0 18px; color: #fff; white-space: nowrap; text-align: center; font-size: 14px; border: none; border-radius: 2px; cursor: pointer; ">
开始上传
</button>
</div>
<div>
<input type="text" id="hidfilenames" />
</div>
</div>
<div>
<input type="hidden" id="hiduserid" value="1" />
<input type="button" value="提交" onclick="save()" />
</div>
<script type="text/javascript">
$(document).ready(function ()
//开始上传
$("#ctlBtn").click(function ()
uploader.upload();
);
var uploader = WebUploader.create(
// 选完文件后,是否自动上传。
auto: false,
// swf文件路径
swf: '~/Scripts/webuploader/Uploader.swf',//这个地方换成自己文件存放的路径
// 文件接收服务端。
server: '/Content/UpLoadProcess', //控制器动作路径
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
// 只允许选择图片文件。
accept:
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
);
var $list = $("#fileList");
var thumbnailWidth = "100";
var thumbnailHeight = "100";
uploader.on('fileQueued', function (file)
var $li = $(
'<div style="display:inline-block;margin-left:10px" id="' + file.id + '" class="file-item thumbnail">' +
'<img>' +
'<div class="info"></div>' +
'<img src="/image/1.jpg" style="width:40px;height:40px;" class="delimg" id="delimg" style="cursor:pointer"/>' + //这个是删除小图标,自己可以随意下载就行
'</div>'
),
$img = $li.find('img[id!=delimg]');
// $list为容器jQuery实例
$list.append($li);
// 创建缩略图
// 如果为非图片文件,可以不用调用此方法。
// thumbnailWidth x thumbnailHeight 为 100 x 100
uploader.makeThumb(file, function (error, src)
if (error)
$img.replaceWith('<span>不能预览</span>');
return;
$img.attr('src', src);
, thumbnailWidth, thumbnailHeight);
);
//删除预览图片
$list.on("click", "#delimg", function ()
var ID = $(this).parent().attr('id');
var quID = uploader.getFile(ID);
uploader.removeFile(quID);
$(this).parent().remove();
)
uploader.on('uploadSuccess', function (file, response)
var v = $("#hidfilenames").val();
$("#hidfilenames").val(v + ',' + response.filePath);
);
uploader.on('uploadFinished', function (file, response)
//所有图片上传成功回调函数
alert("上传成功");
$(".delimg").hide();
);
uploader.on('uploadError', function (file)
//文件上传失败,显示上传出错。
);
)
function save()
alert($("#pid").val());
alert($("#txtcon").val());
alert($("#hidfilenames").val());
alert($("#hiduserid").val());
//此处调api 去实现评论功能
</script>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
public class ContentController : Controller
// GET: Content
public ActionResult Index(int pid)
ViewBag.Pid = pid;
return View();
public ActionResult UpLoadProcess(string id, HttpPostedFileBase file)
string filePathName = string.Empty;
string localPath = "../Img/";
if (Request.Files.Count == 0)
return Json(new jsonrpc = 2.0, error = new code = 102, message = "保存失败" , id = "id" );
file.SaveAs(Server.MapPath(localPath + file.FileName));
return Json(new
jsonrpc = "2.0",
id = id,
filePath = "/Img/" + file.FileName
);
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace WebApplication2
/// <summary>
/// upfile 的摘要说明
/// </summary>
public class upfile : IHttpHandler
public void ProcessRequest(HttpContext context)
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
HttpPostedFile file = context.Request.Files["files"];
string uploadPath =HttpContext.Current.Server.MapPath("../Img/") + "\\";
if (file != null)
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
file.SaveAs(uploadPath + file.FileName);
//下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
string newName = file.FileName;
string oldName = file.FileName;
context.Response.Write("\"newName\": \"" + newName + "\", \"oldName\": \"" + oldName + "\"");
else
context.Response.Write("0");
public bool IsReusable
get
return false;
ashx
asp.net mvc中上传图片立即显示怎么弄
html5的话可以直接显示,可以用flash插件,不然只能上传后再显示 参考技术A 插件Uploadify上传预览 参考技术B 可以上传成功后直接指定显示就好了。以上是关于mvc视图中怎么上传图片并显示的主要内容,如果未能解决你的问题,请参考以下文章