添加上传图片前台显示

在这里插入图片描述

    <table style="border-collapse:separate; border-spacing:100px 20px;">
        <tr>
            <td>名称:</td>
            <td>
                <input id="foodname" type="text" />
            </td>
        </tr>
        <tr>
            <td>价钱:</td>
            <td>
                <input id="jq" type="text" />
            </td>
        </tr>
        <tr>
            <td>描述:</td>
            <td>
                <input id="ms" type="text" />
            </td>
        </tr>
        <tr>
            <td>菜品类型:</td>
            <td>
                <input id="lx" type="text" />
            </td>
        </tr>
        <tr>
            <td>图片</td>
            <td>
                <div style="position: relative;">
                    <input id="Material_Image" style="position: absolute; top: 0; bottom: 0; left: 0;right: 0; opacity: 0;" type="file" accept="image/gif, image/jpg, image/png" onchange="showImg(this)" />
                    <div style="text-align:top">
                        <span style="font-size: 12px;"></span>
                        <img id="upload" src="http://localhost:62533/img/0.jpg" style="width: 40px; height: 40px; vertical-align: middle;" />
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input id="Buttonadd" type="button" value="保存" onclick="Add()" />
            </td>
        </tr>
    </table>
</div>
function Add() {
    var fileUpload = $("#Material_Image").get(0);
    var file = fileUpload.files[0];
    var data = new FormData();
    data.append(file.name, file);
    var obj = {
        Food_Name: $("#foodname").val(),
        Food_Price: $("#jq").val(),
        Food_Describe: $("#ms").val(),
        FoodType_Id: $("#lx").val()
    }
    $.ajax({
        url: "/ValuesController1/AddFood?ff=" + JSON.stringify(obj),
        type: "post",
        data: data,
        contentType: false,
        processData: false,
        success: function (data) {
            if (data > 0) {
                alert("添加成功!");
                location.href = 'img';
            }
            else {
                alert("添加失败!");
            }
        }
    })
}
function showImg(input) {
    var file = input.files[0];
    var reader = new FileReader()
    // 图片读取成功回调函数
    reader.onload = function (e) {
        document.getElementById('upload').src = e.target.result
    }
    reader.readAsDataURL(file)
}
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页