.Net MVC 用 ajaxfileupload 上传图片

本文介绍了一个ASP.NET项目中实现图片上传及预览功能的方法。通过使用jQuery进行Ajax异步上传,并在前端实时预览所选图片,同时详细展示了如何在控制器中处理上传的图片文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入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无法识别

121706_CbSn_3556610.png

 

转载于:https://my.oschina.net/u/3556610/blog/1825855

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值