.Net MVC 用 ajaxfileupload 上传图片

导入js

<script src="~/Scripts/ajaxfileupload.js"></script>

cshtml

<style>
   #oDiv {
      height: 200px;
      width: 200px;
      border: 1px solid #000;
      text-align: center;
      margin-bottom: 10px;
    }
</style>

<div class="all">
    <div id="oDiv">
        <img src="" id="showPic" style="height:100%;width:100%" />
    </div>
    <input type="file"  id="oInput" name="file" onchange="upload_cover(this)"/>
    <input type="text" id="ImageUrl" name="ImageUrl" placeholder="defaultPath" value="" />
</div>  

主要是type="file"的input ,特别注意,它的name="file", 后台接收写的样式一定也要是file

js

function upload_cover(obj) {
    //回传后缀
    var filePath = $("input[name='file']").val();
    var extStart = filePath.lastIndexOf(".");
    var ext = filePath.substring(extStart, filePath.length).toUpperCase();

    ajax_upload(obj.id, function (data) { //function(data)是上传图片的成功后的回调方法
        var isrc = data.relatPath.replace(/\/\//g, '/'); //获取的图片的绝对路径
        $('#image').attr('src', basePath + isrc).data('img-src', isrc); //给<input>的src赋值去显示图片
    }, ext);
}

//具体的上传图片方法
function ajax_upload(feid, callback, ext) {
    if (image_check(feid)) {
        $.ajaxFileUpload({
            url: "/Company/UploadImage",
            secureuri: false,
            fileElementId: feid,
            dataType: 'json',
            data: {fileType: ext},//增加推送的属性
            type: 'post',
            async: true,
            secureuri: false,
            success:
            function (data) {
                alert(data.imagePath);
                $("#ImageUrl").val(data.imagePath);
                $("#showPic").attr("src", data.imagePath);
            },
            error:
            function (data) {
                alert(data);
            }
        });
    }
    };
    function image_check(feid) { //自己添加的文件后缀名的验证
        var img = document.getElementById(feid);
        return /.(jpg|png|gif|bmp)$/.test(img.value) ? true : (function () {
            modals.info('图片格式仅支持jpg、png、gif、bmp格式,且区分大小写。');
            return false;
        })();
    }
        

controller

[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file)
{
    //获取图片后缀
    string fileType = Request.Form["fileType"];
    // 时间
    string now =  DateTime.Now.ToString("yyyyMMddHHmmssffff");
    //文件存放的文件路径
    string folder = HttpContext.Server.MapPath("/Content/images/companies/");

    // 保存文件
    string filePath = Path.Combine(folder, now + fileType);
    file.SaveAs(filePath);
    //切出相对路径
    string subFilePath = filePath.Substring(filePath.LastIndexOf("\\Content"));
    JsonResult json = new JsonResult();
    json.ContentType = "text/html";
    json.Data = new { imagePath = subFilePath, success = true };

    return json;
    //return Content(filePath);
}

注意: UploadImage(HttpPostedFileBase file){} 里面的file 一定要是前台 name="file"

返回的json不可以直接回传,需要新建一个JsonResult , 备注json.ContentType = "text/html"; 否则默认是application/json,前台html无法识别

猜你喜欢

转载自my.oschina.net/u/3556610/blog/1825855