MVC 图片预览

1.页面cshtml

<form name="frmInput" id="frmInput" method="post" action="@Url.Action(ViewContext.RouteData.Values["Action"].ToString())" enctype="multipart/form-data" >
   <div class="form-group col-md-6">
    <label class="control-label col-md-4">
        图片一
    </label>
    <div class="col-md-8 input-group">
        <ul class="list-unstyled">
            <li style="float: left; width: 180px;position:relative;">
                <img src="@Url.Content(Model.MDetailImageUrl)" alt="图片" width="140" />
                <input class="input_file" id="TDetailImageUrl" type="file" name="TDetailImageUrl"  tid="5" onchange="ImagePreview(this)" />
            </li>
        </ul>
    </div>
</div>
<div class="form-group col-md-6">
    <label class="control-label col-md-4">
        图片二
    </label>
    <div class="col-md-8 input-group">
        <ul class="list-unstyled">
            <li style="float: left; width: 180px;position:relative;">
                <img src="@Url.Content(Model.MDetailImageUrl)" alt="图片" width="140" />
                <input class="input_file" id="MDetailImageUrl" type="file" name="MDetailImageUrl"  tid="6" onchange="ImagePreview(this)" />
            </li>
        </ul>
    </div>
</div>
<input type="button" value="保存" onclick="Input.Save(this)" class="btn-8" />
</from>

2.js

路径:@Html.Hidden("ImagePreviewUrl", Url.Action("ImagePreview"))

//图片预览
    function ImagePreview(e) {
        if ($(e).val() == "") {
            alert("请选择一个图片文件,再点击上传。");
            return;
        }

        $(e).closest("form").ajaxSubmit({
            url: $("#ImagePreviewUrl").val() + "?name=" + $(e).attr("name"),
            success: function (data, status) {
                if (status == "success" && data != "") {
                    $(e).parent().children("img").attr("src", data);
                }
                else {
                    alert("图片格式不对");
                }
            }
        });
    }

3.后台
ImagesAPPI.PreviewDataForSingle为自定义方法,返回的是base64数据

public string ImagePreview(string name)
        {
            int fileIndex = 0;
            string result="";
            if (Request.Files.Count > 0)
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    if (!string.IsNullOrWhiteSpace(Request.Files[i].FileName))
                    {
                        string inputName = Request.Files.AllKeys[i];
                        if (!string.IsNullOrWhiteSpace(inputName) && name == inputName)
                        {
                            fileIndex = i;
                            break;
                        }
                    }
                }
                result = ImagesAPPI.PreviewDataForSingle(Request.Files[fileIndex], 150, 150); 
            }
            return result;
        }

 

你可能感兴趣的:(MVC 图片预览)