• 页面上传数据到服务器再保存到数据库表(.net项目)


    上传组件plupload学习

    突然就明白了项目的上传文件是怎么回事了,防止以后遗忘,趁着热乎赶紧记下来。

    页面html

     <div id="tableDialogMaintenanceOrderToolbar">
            <form id="frmDialogMaintenanceOrder" method="post">
                <table>                                          
                </table>
            </form>
     </div>
    
     <div id="dlgAddUpdateMaintenanceOrderInfoButtons">
            <table style="100%">
                <tr>
                    <td >
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="beehunt.uploadFile()" id="btnSaveButton" name="btnSaveButton">上传附件</a>
                        <a >保存</a>
                        <a >取消</a>
                        <label style="padding-left:10px"><input type="checkbox" >继续录入</label>
                    </td>
                    <td align="right" style=" 440px; font-size:12px">
                        <span>记录数:<label >0</label> ,总数量:<label >0</label></span>
                    </td>
                </tr>
            </table>
     </div>
    

    引用的index.js

    //上传附件
    uploadFile: function () {
            $.messager.alert('上传', "<input type='button' value='上传附件' id='btnUploadFileeee' /><br/>附件中包含下列项目文件,");
            pploads.init(false, 'btnUploadFileeee', "/api/Upload/UploadFile", "doc,docx,ppt,pptx,xls,xlsx,pdf", js_UploadFile.uploadOkProjectFiles);
    },
    

    引用的upload.js

    $(function () {
        UploadFile.init();
    });
    
    var UploadFile = {
        init: function () {
            js_UploadFile.upload();
        },
    };
    
    var js_UploadFile = {
        imgIndex: 0,
        upload: function () {
            pploads.init(false, "btnUploadFiles", "/api/Upload/UploadFile", "doc,docx,ppt,pptx,xls,xlsx,pdf", js_UploadFile.uploadOkHeadPhoto);
        },
        uploadOkHeadPhoto: function (file, response) {
            response = $.parseJSON(response);
            if (!response.IsSuccess) return;
    
            var subTable = $('#tableRsMaintenanceMenu');//main datagrid id
            var maintenanceOrderPriceId = subTable.datagrid('getSelected').Id;
    
            var originalFileName = file.name; //原始文件名
            var url; //上传文件的url地址
            var physicalFullFilename; //上传文件的物理全路径
            if (response.Data.length > 1) {
                url = response.Data[0].replace(""", "").replace(""", "");
                physicalFullFilename = response.Data[1];
    
                beehunt.ajax({
                    url: '/api/RsMaintenanceOrderPriceFiles/AddUploadFile',
                    data: { maintenanceOrderPriceId: maintenanceOrderPriceId, Path: physicalFullFilename, Url: url, OriginName: originalFileName },
                    callback: function () {
                        dialog.dialog('destroy');
                    }
                });
            }
        },
    
    
        uploadOkProjectFiles: function (file, response) {
            response = $.parseJSON(response);
            if (!response.IsSuccess) return;
    
            var subTable = $('#tableRsMaintenanceMenu');//main datagrid id
            var maintenanceOrderPriceId = subTable.datagrid('getSelected').Id;
    
            var originalFileName = file.name; //原始文件名
            var url; //上传文件的url地址
            var physicalFullFilename; //上传文件的物理全路径
            if (response.Data.length > 1) {
                url = response.Data[0].replace(""", "").replace(""", "");
                physicalFullFilename = response.Data[1];
    
                beehunt.ajax({
                    url: '/api/RsMaintenanceOrderPriceFiles/AddUploadFile',
                    data: { maintenanceOrderPriceId: maintenanceOrderPriceId, Path: physicalFullFilename, Url: url, OriginName: originalFileName },
                    callback: function () {
                        dialog.dialog('destroy');
                    }
                });
            }
        },
    
    };
    

    使用上传组件plupload,绑定触发文件选择对话框的DOM元素。

    引用的 plugin/pluploadcom.js 实例化一个plupload对象

    var pploads = {
        init: function (isshowdg, btn, url, filetype, okcallback, addcallback, isbtnSubmit, filesize) {
    
            //限制上传大小
            filesize = (filesize == undefined || filesize == null) ? 2 : filesize;
    
            var uploaderbb = new plupload.Uploader({
                runtimes: 'html5,flash,silverlight,html4,browse',
                browse_button: btn,
                url: url,
                flash_swf_url: '../js/plugin/plupload/Moxie.swf',
                silverlight_xap_url: '../js/plugin/plupload/Moxie.xap',
    
                unique_names: true,
                multi_selection: false,
                filters: {
                    prevent_duplicates: false,
                    max_file_size: filesize + 'mb',
                    mime_types: [
                        { title: "files", extensions: filetype }
                    ]
                },
    
                init: {
                    PostInit: function () {
                        //require("plugin/plupload/i18n/zh_CN.js");
                        // Chinese (China) (zh_CN)
                        plupload.addI18n({ "Stop Upload": "停止上传", "Upload URL might be wrong or doesn't exist.": "上传的URL可能是错误的或不存在。", "tb": "tb", "Size": "大小", "Close": "关闭", "Init error.": "初始化错误。", "Add files to the upload queue and click the start button.": "将文件添加到上传队列,然后点击”开始上传“按钮。", "Filename": "文件名", "Image format either wrong or not supported.": "图片格式错误或者不支持。", "Status": "状态", "HTTP Error.": "HTTP 错误。", "Start Upload": "开始上传", "mb": "mb", "kb": "kb", "Duplicate file error.": "重复文件错误。", "File size error.": "文件大小错误。", "N/A": "N/A", "gb": "gb", "Error: Invalid file extension:": "错误:无效的文件扩展名:", "Select files": "选择文件", "%s already present in the queue.": "%s 已经在当前队列里。", "File: %s": "文件: %s", "b": "b", "Uploaded %d/%d files": "已上传 %d/%d 个文件", "Upload element accepts only %d file(s) at a time. Extra files were stripped.": "每次只接受同时上传 %d 个文件,多余的文件将会被删除。", "%d files queued": "%d 个文件加入到队列", "File: %s, size: %d, max file size: %d": "文件: %s, 大小: %d, 最大文件大小: %d", "Drag files here.": "把文件拖到这里。", "Runtime ran out of available memory.": "运行时已消耗所有可用内存。", "File count error.": "文件数量错误。", "File extension error.": "文件扩展名错误。", "Error: File too large:": "错误: 文件太大:", "Add Files": "增加文件" });
                    },
    
                    FilesAdded: function (up, files) {
                        $(uploaderbb.files).each(function (i, file) {
                            if (file != files[files.length - 1])
                                uploaderbb.removeFile(file);
                        });
    
                        if (addcallback != undefined && addcallback != null) {
                            var f = addcallback(files);
                            if (!f) {
                                plupload.each(files, function (file) {
                                    uploaderbb.removeFile(file);
                                });
                                if (isshowdg == true) //需要弹框显示上传百分比
                                    $("#uploadfileQueueCls").slideUp();
                                return f;
                            }
                        }
    
                        if (isshowdg == true) {  //需要弹框显示上传百分比
                            var x = $(window).width() - $("#uploadfileQueueCls").outerWidth();
                            var y = $(window).height() - $("#uploadfileQueueCls").outerHeight() + $(window).scrollTop();
    
                            $("#filelist").empty();
                            $("#uploadfileQueueCls").slideDown().css({ top: y + "px", left: x + "px" }).find(".tc-close").click(function () { $("#uploadfileQueueCls").slideUp(); });
    
                            plupload.each(files, function (file) {
                                $("#filelist").append('<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>');
                            });
                        }
                        if (isbtnSubmit == undefined || isbtnSubmit == null || isbtnSubmit == false)
                            uploaderbb.start();
                    },
    
                    UploadProgress: function (up, file) {
                        $("#" + file.id + " b").eq(0).html('<span>' + file.percent + "%</span>");
                    },
    
                    Error: function (up, err) {
                        if (isshowdg == true) //需要弹框显示上传百分比
                            $("#uploadfileQueueCls").slideUp();
    
                        if (err.code == -600)
                            beehunt.message({ title: "错误", msg: "超出文件大小2M" });
                        else
                            beehunt.message({ title: "错误", msg: err.message });
                        //document.getElementById('console').innerHTML += "
    Error #" + err.code + ": " + err.message;
                    },
    
                    //单个文件上传完成
                    FileUploaded: function (up, files, xhr) {
    
                        if (okcallback != undefined && okcallback != null && typeof (okcallback) == "function") {
                            if (okcallback.length > 1)
                                okcallback(files, xhr.response);
                            else
                                okcallback(xhr.response);
                        }
                    },
                    //整个队列上传完成
                    UploadComplete: function (up, files, response) {
                        plupload.each(files, function (file) {
                            uploaderbb.removeFile(file);
                        });
                        if (isshowdg == true) //需要弹框显示上传百分比
                            setTimeout(function () { $("#uploadfileQueueCls").slideUp(); }, 2000);
                    }
                }
            });
    
            uploaderbb.init();
    
            return uploaderbb;
        }
    };
    

    Contorller

    class UploadFile

    /// <summary>
            /// 上传文件
            /// </summary>
            /// <returns></returns>
            public JsonResult UploadFile(int? id, bool isCreateThum = true, int w = 0, int h = 0)
            {
                var result = new ResultSet<string[]>();
    
                try
                {
                    HttpFileCollectionBase httpPostFileList = Request.Files;
    
                    if (null == httpPostFileList || httpPostFileList.Count <= 0)
                    {
                        result.VaildList.Add(new VaildInfo() { Code = "", Message = Lang.Error_Upload_Null });
                        result.IsSuccess = false;
                        return Json(result);
                    }
    
                    if (httpPostFileList[0].ContentLength > (5 * (1024 * 1024)))
                    {
                        result.VaildList.Add(new VaildInfo() { Code = "", Message = Lang.UploadSizeBig });
                        result.IsSuccess = false;
                        return Json(result);
                    }
    
    
                    result.Data = FileOperater.SaveAttachment(httpPostFileList[0]);
                       
                    result.IsSuccess = true;
                }
                catch (Exception e)
                {
                    Logger.Error(e.Message, e);
                    result.IsSuccess = false;
                    result.Message = e.Message;
                }
                return Json(result);
            }
    

    class FileOperater

    /// <summary>
            /// 保存附件
            /// </summary>
            /// <param name="httpPostFile"></param>
            /// <param name="saveDir"></param>
            /// <returns></returns>
            public static string[] SaveAttachment(HttpPostedFileBase httpPostFile, string saveDir = "temp", bool isCreateThum = false)
            {
                string[] result = new string[] { };
                string defaultUrl = WebConfig.UpLoadUrl;
                string defaultRoot = WebConfig.UpLoadPosition;
                FileOperaterClient fileOperaterClient = new FileOperaterClient();
    
                try
                {
                    var extentName = httpPostFile.FileName.Substring(httpPostFile.FileName.LastIndexOf("."));
                    var fileName = string.Format("{0}{1}", CommonHelper.Tooken, extentName);
    
                    var inputStream = httpPostFile.InputStream;
                    if (inputStream != null && inputStream.Length > 0)
                    {
                        byte[] buffer = new byte[(int)inputStream.Length];
                        inputStream.Read(buffer, 0, buffer.Length);
    
                        // 调用服务保存文件
                        result = fileOperaterClient.Save(buffer, fileName, saveDir, defaultRoot, defaultUrl, isCreateThum);
                    }
                }
                catch (Exception ex)
                {
                    fileOperaterClient.Abort();
                    Logger.Error(ex);
                }
                finally
                {
                    if (fileOperaterClient.State != System.ServiceModel.CommunicationState.Faulted)
                    {
                        fileOperaterClient.Close();
                    }
                }
    
                return result;
            }
    

    好了,到此,文件已经上传到服务器了。

    下面是将上传的文件信息保存到数据表

    在调用plupload的代码中

    pploads.init(false, "btnUploadFiles", "/api/Upload/UploadFile", "doc,docx,ppt,pptx,xls,xlsx,pdf", js_UploadFile.uploadOkHeadPhoto);
    

    js_UploadFile.uploadOkHeadPhoto是一个回调函数,文件上传完成时调用。

    uploadOkProjectFiles: function (file, response) {
            response = $.parseJSON(response);
            if (!response.IsSuccess) return;
    
            var subTable = $('#tableRsMaintenanceMenu');//main datagrid id
            var maintenanceOrderPriceId = subTable.datagrid('getSelected').Id;
    
            var originalFileName = file.name; //原始文件名
            var url; //上传文件的url地址
            var physicalFullFilename; //上传文件的物理全路径
            if (response.Data.length > 1) {
                url = response.Data[0].replace(""", "").replace(""", "");
                physicalFullFilename = response.Data[1];
    
                beehunt.ajax({
                    url: '/api/RsMaintenanceOrderPriceFiles/AddUploadFile',
                    data: { maintenanceOrderPriceId: maintenanceOrderPriceId, Path: physicalFullFilename, Url: url, OriginName: originalFileName },
                    callback: function () {
                        dialog.dialog('destroy');
                    }
                });
            }
        },
    

    通过ajax请求与后台交互,把文件信息保存到数据库中。

     

  • 相关阅读:
    django4-模板进阶
    django3-视图函数进阶
    django1-web开发基础知识
    django2-登录与出版社
    django3-路由系统进阶
    web前端-bootstrap
    Java发送邮件--web.xml配置,Java代码配置
    yii框架美化访问路径,去掉index.php/?r=部分
    JAVA集合框架的特点及实现原理简介
    详解:Java字符串类型"switch"的底层原理
  • 原文地址:https://www.cnblogs.com/tooy/p/7777190.html
Copyright © 2020-2023  润新知