.net attachment upload and download function examples

Updating files:

If the effect is shown:

After selecting a file on the computer, the display effect is as follows:

You can delete the uploaded attachments, or you can continue to upload the attachments. The specific logic is as follows:

The front-end receives the file information selected by the user, and then transmits it to the back-end, and the back-end saves the file to the specified directory on the server.

Front-end HTML code:

 <div class="form-group col-xs-6 modal-form" id="div_AUDIT_ATTACHMENT"> 
   <label class="col-xs-5 control-label">装修审核相关附件</label> 
   <input type="hidden" name="AUDIT_ATTACHMENT" id="id_AUDIT_ATTACHMENT" class="fld_senlan file_mark" value="" />
   <div class="col-xs-7 bxRem positionRe textDiv" id="AddFile_AUDIT_ATTACHMENT">
    <input type="file" id="file_AUDIT_ATTACHMENT" name="AUDIT_ATTACHMENT" class="form-control length_valid input-md Mroad" multiple="multiple" onchange="onc('AUDIT_ATTACHMENT')" />
    <p class="help-block" id="p_AUDIT_ATTACHMENT"></p>
    <div class="bxRem ZfileList" id="Add_FileView"></div>
   </div>
  </div> 

Front-end js code: 

//附件上传
function onc(fieldname) {
    var pd = 0;
    var files = document.getElementById("file_" + fieldname).files;//当前选择附件信息
    for (var i = 0; i < files.length; i++) {
        $("#Add_FileView").find('a').each(function () {
            var aFile = $(this).children("span")[0].innerText;
            if (files[i].name == aFile) {
                alert("请勿上传相同文件");
                pd = 1;
            }
        })

        var re = /[`~!@#$%^&*_+=<>{}\/'[\]]/im;
        if (re.test(files[i].name)) {
            alert("文件名中不允许存在 `~!@#$%^&*_+=<>{}\/'[] 等特殊字符");
            pd = 1;
        }
    }
    if (pd == 1) {
        $('#file_' + fieldname).val('');
        return false;
    }
    var maxSize = 15 * 1024 * 1024;
    var formData = new FormData();
    var loggerString = "";
    for (var i = 0; i < files.length; i++) {
        var $name = files[i].name;
        var file = files[i].size;
        if (!/.(gif|jpg|jpeg|png|pdf|bmp|xls|xlsx|doc|docx|txt|rar|zip|arj|z|cab|lzh|ace|tar|gz|uue|bz2|jar|iso)$/.test($name.toLowerCase())) {
            alert("上传的文件格式不正确,请重新上传!");
            $('#file_' + fieldname).val('');
            return;
        }
        if (file > maxSize) {
            alert('上传的文件大小不能超过15M,请重新上传!');
            $('#file_' + fieldname).val('');
            return;
        }
        formData.append('file' + i, files[i]);
        loggerString += ("file" + i + ":" + files[i].name + ",");
    }

    $.ajax({
        url: "AssetManage_UploadFiles.aspx",
        data: formData,
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须
        type: "post",
        success: function (data) {
            var strFileA = "";
            if (data && data.length > 0) {
                var fileId = $('#id_' + fieldname).val();
                for (var i = 0; i < data.length; i++) {
                    strFileA += "<div id=\"btn_File" + data[i].fileId + "\"><a href='." + data[i].filePath + "' target=\"_Blank\" fid='" + data[i].fileId + "' value='" + data[i].fileName + "' title='" + data[i].fileName + "' title='" + data[i].fileName + "'><span>" + data[i].fileName + "</span></a>";
                    strFileA += "<input type=\"button\" value=\"删除\"  onclick=\"Del_File('" + data[i].fileId + "','" + fieldname + "')\"></div>";

                    if (fileId != "" && fileId != undefined) {
                        fileId = fileId + "," + data[i].fileId;
                    }
                    else {
                        fileId = data[i].fileId;
                    }
                }
                $('#id_' + fieldname).val(fileId);
            }
            $('#file_' + fieldname).val('');
            $('#file_' + fieldname).siblings('#Add_FileView').append(strFileA);
            //$("#Add_FileView").append(strFileA);
        }
    })
}

Backend code:

 public class AssetsFileSave : WebPageBase4json
    {
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private string path;
        string id = "";
        protected override string getReturnJson(HttpContext context, List<OptReturnData> lobj)
        {
            string filePath = "/UpFile/XDCYASCHD/";
            string json = "";
            try
            {
                HttpFileCollection files = context.Request.Files;

                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                        string stamp = DateTime.Now.ToString("yyyyMMddhhmmss");
                        string date = DateTime.Now.ToString("yyyyMMdd");
                        string Folder = "~/UpFile/XDCYASCHD/" + date;
                        filePath += date;
                        //如果不存在就创建file文件夹 
                        if (!Directory.Exists(HttpContext.Current.Server.MapPath(Folder)))
                        {
                            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(Folder));
                        }
                        string tempfileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);

                        //存储到本地路径
                        path = Folder + "/" + stamp + tempfileName;
                        string newFileName = stamp + tempfileName;
                        filePath += ("/" + stamp + tempfileName);
                        string savepath = HttpContext.Current.Server.MapPath(path);

                        file.SaveAs(savepath);

                        logger.Debug("上传成功,路径:" + HttpContext.Current.Server.MapPath(path));
                        
                        filePath = "/UpFile/XDCYASCHD/" + date + "/" + newFileName;
                        InserNoticeFile(filePath, tempfileName, context.Session["Acount"].ToString(), newFileName);

                        json += "{\"fileId\":\"" + id + "\",\"filePath\":\"" + filePath + "\",\"fileName\":\"" + tempfileName + "\"},";
                    }
                }
                else
                {
                    new Exception("无法获取上传文件");
                }
            }
            catch (Exception ex)
            {
                logger.Error("异常描述:\t" + ex.Message);
                logger.Error("异常方法:\t" + ex.TargetSite);
                logger.Error("异常堆栈:\t" + ex.StackTrace);
            }

            json = "[" + json.TrimEnd(',') + "]";

            return json;
        }
        
        private void InserNoticeFile(string FILEPATH, string FILENAME, string CREATE_USER, string fonname)
        {
            using (OracleConnection conn = new OracleConnection(DefaultDBConnection))
            {
                conn.Open();//打开连接

                //获取文件ID
                string sql = "select SEQ_T_DUP_DATAFILE.nextval id from dual";
                OracleCommand cmd = new OracleCommand(sql, conn);
                OracleDataAdapter ada = new OracleDataAdapter(cmd);
                DataSet ds = new DataSet();
                ada.Fill(ds);
                id = ds.Tables[0].Rows[0]["ID"].ToString();

                string SQL = @"insert into T_DUP_DATAFILE(FID, FPATH, FNAME, CREATE_USER, CREATE_DATE, FONNAME) values(:FID,:FPATH,:FNAME,:CREATE_USER,sysdate,:FONNAME)";
                cmd = new OracleCommand(SQL, conn);
                cmd.Parameters.Add("FID", id);
                cmd.Parameters.Add("FPATH", FILEPATH);
                cmd.Parameters.Add("FNAME", FILENAME);
                cmd.Parameters.Add("CREATE_USER", CREATE_USER);
                cmd.Parameters.Add("FONNAME", fonname);
                int i = cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

    }

 

Database table structure (oracle):

 

Backend logic: save the attachment file delivered by the front end to the specified directory of the server, and then save the attachment information (attachment path, attachment name, etc.) in the attachment table of the database. The attachment field of the business table only needs the file in the attachment table ID is fine.

 

Comparison of page DOM elements before and after attachment upload:

 

Attachment deletion:

Front-end js code:

//删除附件
function Del_File(obj, fieldname) {
    var id = 'btn_File' + obj;
    var jd = document.getElementById(id);
    jd.parentNode.removeChild(jd);
    var fileValue = $('#id_' + fieldname).val();
    if ((fileValue.search(',') == -1 || fileValue.search(obj + ',') == -1) && (fileValue.search(obj) != -1)) {
        if (fileValue.search(obj + ',') == -1 && fileValue.search(',' + obj) != -1) {
            fileValue = fileValue.replace(',' + obj, '');
        }
        else {
            fileValue = fileValue.replace(obj, '');
        }
    }
    else {
        fileValue = fileValue.replace(obj + ',', '');
    }

    $('#id_' + fieldname).val(fileValue);
}

The function of the above code is to remove the element from the page, then delete the ID of the corresponding attachment from the hidden field, and update the attachment field value in the database record when the page submits data.

 

Attachment loading:

For example, when viewing the page, you need to load the uploaded attachments and you can download them. The page effect is as shown in the figure:

Click the name of the attachment to download or open the corresponding attachment.

Front-end code:

//加载附件
//fldname 附件字段名称
//fileid 附件id
function loadFile(fldname, fileid) {
   if (fldname != undefined && fldname != null && fldname != '' && fileid != undefined && fileid != null && fileid != '') {
        $.ajax({
            url: "AssetManage_GetFileInfo.aspx",
            data: { FID: fileid },
            async: false,
            type: "post",
            success: function (data) {
                var filelist = data[0].OptRetData.Table;
                var strFileA = "";
                if (filelist && filelist.length > 0) {
                    for (var i = 0; i < filelist.length; i++) {
                        strFileA += "<div id=\"btn_File" + filelist[i].FID + "\"><a href='." + filelist[i].FPATH + "' target=\"_Blank\" fid='" + filelist[i].FID + "' value='" + filelist[i].FNAME + "' title='" + filelist[i].FNAME + "'><span>" + filelist[i].FNAME + "</span></a></div>";
                    }
                }
                $("#AddFile_" + fldname + " #Add_FileView").append(strFileA);
            }
        });
    }
}

 

The above code is just a reference example. If you want to use it, you need to change it according to the actual situation. The background code is written in a custom frame and is only for reference.

 

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/114220110