.net core使用百度webupload上传图片

后端代码:

/// <summary>
        /// 图片上传,上传路径: "/Uploads/Images/" + folder + "/" + saveName
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadImage([FromServices]IWebHostEnvironment environment,string folder)
        {
            try
            {
                var files = Request.Form.Files;
                //string contentRootPath = environment.ContentRootPath;//项目所在路径
                string webRootPath = environment.WebRootPath;//wwwroot文件夹所在路径 
                string filePath = webRootPath + "/Uploads/Images/" + folder + "/";
                string fullPath = "";
                string uploadPath = "";

                foreach (var formFile in files)
                {
                    string fileName = Path.GetFileName(formFile.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName).ToLower(); // 文件扩展名
                    string saveName = DateTime.Now.ToString("yyyyMMddhhmmssffff") + fileExtension; // 保存文件名称
                    int filesize = int.Parse(formFile.Length.ToString()) / 1024;//图片大小(KB)
                    if (filesize > 5120 || filesize <= 2 || (fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".gif"))
                    {
                        return Json(new { Success = false, Message = "上传失败!\r请上传jpg/png/gif格式图片,文件大小不要超过5MB也不要小于2K" });
                    }
                    fullPath = Path.Combine(filePath, saveName);
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    using (var stream = new FileStream(fullPath, FileMode.CreateNew))
                    {
                        formFile.CopyTo(stream);
                    }
                    uploadPath = "/Uploads/Images/" + folder + "/" + saveName;
                }

                return Json(new { Success = true, FilePath = uploadPath });
            }
            catch (Exception e)
            {
                NLogHelper.WriteDebug("图片上传方法异常:"+ e.Message.ToString());
                return Json(new { Success = false, Message = e.Message.ToString() });
            }
           
        }

前端代码:

@model Dw.Models.Article.Article_Category
@{
    ViewBag.Title = "文章类别管理";
    Layout = "~/Views/Shared/_Form.cshtml";
}

<script>
    var keyValue = '@ViewBag.keyValue';
    var parentId = '@ViewBag.parentId';
    $(function () {
        initControl();
    })
    //初始化控件
    function initControl() {
        //上级栏目
        $("#ParentId").ComboBoxTree({
            url: "/ArticleManage/ArticleCategory/GetTreeJson",
            description: "==请选择==",
            height: "260px",
            allowSearch: true
        });
        //获取表单
        if (!!keyValue) {
            $.SetForm({
                url: "/ArticleManage/ArticleCategory/GetFormJson",
                param: { keyValue: keyValue },
                success: function (data) {
                    $("#form1").SetWebControls(data);
                }
            });
        } else {
            $("#ParentId").ComboBoxTreeSetValue(parentId);
        }
    }
    //保存表单
    function AcceptClick() {
        if (!$('#form1').Validform()) {
            return false;
        }
        var postData = $("#form1").GetWebControls(keyValue);
        if (postData["ParentId"] == "") {
            postData["ParentId"] = 0;
        }
        $.SaveForm({
            url: "/ArticleManage/ArticleCategory/SaveForm?keyValue=" + keyValue,
            param: postData,
            loading: "正在保存数据...",
            success: function () {
                $.currentIframe().$("#gridTable").resetSelection();
                $.currentIframe().$("#gridTable").trigger("reloadGrid");
            }
        })
    }
</script>
<div style="margin-left: 10px; margin-top: 20px; margin-right: 30px;">
    <table class="form">
        @Html.HiddenFor(model => model.CategoryId)
        @Html.HiddenFor(model => model.CreateDate)
        @Html.HiddenFor(model => model.CreateUserId)
        @Html.HiddenFor(model => model.CreateUserName)
        <tr>
            <th class="formTitle">名称<font face="宋体">*</font></th>
            <td class="formValue" colspan="3">
                @Html.TextBoxFor(model => model.Name, new { type = "text", onblur = "$.ExistField(this.id,'/ArticleManage/ArticleCategory/ExistName')", @class = "form-control" })
            </td>
        </tr>
        <tr>
            <th class="formTitle">上级栏目</th>
            <td class="formValue" colspan="3">
                <div id="ParentId" type="selectTree" class="ui-select">
                </div>
            </td>
        </tr>
        <tr>
            <th class="formTitle">导航图片</th>
            <td class="formValue" colspan="3">
                @*<input type="file" id="picture_upload" name="picture_upload" value='导航图片' />*@
                <div id="uploader">
                    <input type="hidden" value="hid_blog_image"/>
                    <div id="thelist" class="uploader-list"></div>
                    @*<a href="javascript:void(0)" Onclick="remove_pic()" id="minus">
                            <span class="glyphicon glyphicon-remove"></span>
                        </a>*@
                    <!--用来存放文件信息-->
                    <div class="btns">
                        <div id="picker">选择文件</div>
                        @*<button id="ctlBtn" class="btn btn-default">开始上传</button>*@
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <th class="formTitle">图片路径</th>
            <td class="formValue" colspan="3">
                @Html.TextBoxFor(m => m.PictureUrl, new { type = "text", @class = "form-control" })
            </td>
        </tr>
        <tr>
            <th class="formTitle">
                状态
            </th>
            <td class="formValue" colspan="3">
                <select id="EnabledMark" name="EnabledMark">
                    <option value="1">有效</option>
                    <option value="0">无效</option>
                </select>
            </td>
        </tr>
        <tr>
            <th class="formTitle">
                排序
            </th>
            <td class="formValue" colspan="3">
                @Html.TextBoxFor(model => model.SortCode, new { type = "text", @class = "form-control" })
            </td>
        </tr>
        <tr>
            <th class="formTitle" valign="top" style="padding-top: 4px;">
                备注
            </th>
            <td class="formValue" colspan="3">
                @Html.TextBoxFor(model => model.Description, new { type = "text", @class = "form-control", style = "height: 70px;" })
            </td>
        </tr>
    </table>
</div>


<link href="~/scripts/plugins/webuploader/webuploader.css" rel="stylesheet" />
<script src="~/scripts/plugins/webuploader/webuploader.js"></script>
<script type="text/javascript">
    var BASE_URL = '';
    var uploader = WebUploader.create({
        auto: true,
        // swf文件路径
        swf: BASE_URL + '/scripts/plugins/webuploader/Uploader.swf',
        // 文件接收服务端。
        server: '/Uploads/UploadImage?folder=ArticleCategory',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: '#picker',
        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        }
    });

    uploader.on('fileQueued', function (file) {
        $list = $('#thelist');
        $list.append('<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
            '</div>');
    });

    uploader.on('uploadSuccess', function (file, response) {
        var data = eval(response);
        if (data.success) {
            $('#PictureUrl').val(data.filePath);
        }
        else {
            alert(data.message);
        }
        $('#' + file.id).find('p.state').text('已上传');
    });

    uploader.on('uploadError', function (file) {
        $('#' + file.id).find('p.state').text('上传出错');
    });

    uploader.on('uploadComplete', function (file) {
        $('#' + file.id).find('.progress').fadeOut();
    });

    uploader.on('uploadAccept', function (file, response) {
        var data = eval(response);
        if (data.success) {
            $('#thelist').html('<img src="' + data.filePath + '" style="width:200px;margin-bottom:20px" />');
            $('#hid_blog_image').val(data.filePath);
            $('#minus').show();
        }
    });

    function remove_pic() {
        $('#thelist').html('');
        $('#hid_blog_image').val('');
        $('#minus').hide();
    }
</script>

 

webuploader控件地址: http://fex.baidu.com/webuploader/getting-started.html

 

posted @ 2019-12-15 23:29  代码沉思者  阅读(517)  评论(0编辑  收藏  举报