C# 上传文件并将路径存入数据库

xiaoxiao2021-02-28  118

这几天学习过程中学习了上传文件,在这儿总结一下吧! <div> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-print" plain="true" οnclick="addAttach()" style="color:#000;">文件上传</a> </div> 通过一个超链接弹出一个js弹窗并进行文件的上传功能 <div class="easyui-window" id="import-excel-template" title="文件上传" style="width:400px;height:180px;padding:2px;" closed="true"> <form id="importFileForm" method="post" enctype="multipart/form-data" style="display:none"> <table style="margin:5px;height:70px;border:0;"> <tr > <td>文件名称</td> <td><input class="easyui-textbox" name="c_Name" id="c_Name" style="width:260px;height:30px;" data-options="required:true"></td> </tr> <tr > <td>请选择文件</td> <td> <input style="width:260px;height:30px;" class="easyui-filebox" id="fileImport" name="fileImport" data-options="buttonText:'浏览',prompt:'请选择要上传的文件(50M以内)....'"> </td> </tr> </table> <div style="text-align:center;clear:both;margin:5px;"> <a id="uploadFile" οnclick="importFileClick()" href="javascript:void(0)">上传</a> <a οnclick="closeImportClick()">关闭</a> </div> </form> </div> 为了弹窗稍微美观一些,所以采用了easyui对弹窗以及输入框的定义。因为上传文件输入的二进制流,所以form表单中需要加入enctype="multipart/form-data"。 //上传文件 function addAttach() { $('#import-excel-template').window('open') document.getElementById("importFileForm").style.display = "block"; } 点击超链接打开Windows弹窗,其中import-excel-template对应的是easyui-window的id //关闭导入弹出窗口 function closeImportClick() { $("#importFileForm")[0].reset(); $('#import-excel-template').window('close') }       上传文件提交到后台 //导入文件 var savePath = null; function importFileClick() { var name = escape($("#c_Name").val()); //escape()对字符串进行编码,这里解决了在IE上的乱码问题 if (name == null || name == "") { layer.msg('请输入文件名'); return; //要求必须输入文件名 } //获取上传文件控件内容 var temp = $("#fileImport").next().children("[type='file']"); var file = document.getElementById(temp.attr("id")).files[0]; // var file = document.getElementByName("c_ProFile")[0].files[0]; 判断控件中是否存在文件内容,如果不存在,弹出提示信息,阻止进一步操作 if (file == null || file == "") { layer.msg('错误,请选择文件'); return; } //获取文件名称 //var fileName = file.name; //计算文件大小 //如果文件大小大于1024字节X1024字节,则显示文件大小单位为MB,否则为KB if (file.size > 1024 * 1024) { fileSize = Math.round(file.size * 100 / (1024 * 1024)) / 100; if (fileSize > 50) { layer.msg('错误,文件超过50MB,禁止上传!'); return; } fileSize = fileSize.toString() + 'MB'; } else { fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; } //将文件名和文件大小显示在前端label文本中 //document.getElementById('fileName').innerHTML = "<span style='color:Blue'>文件名: " + file.name + ',大小: ' + fileSize + "</span>"; // 获取form数据 var formData = new FormData($("#importFileForm")[0]); //调用controller后台action方法,将form数据传递给后台处理。contentType必须设置为false,否则chrome和firefox不兼容 $.ajax({ url: "SaveAttach?name="+name, type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (result) { //上传成功后将控件内容清空,并显示上传成功信息 if (result.success) { layer.msg(result.errorMsg); closeImportClick(); } else { layer.msg(result.errorMsg); return; } } }); } 在表单里只有一个文件名的情况下,我就直接传到了后台,当有多个数据的时候采用的是将数据封装成一个json传送,也不知道这样安全性够不够高,欢迎大家一起思考并给予指正。 public JsonResult SaveAttach(string name="") { Hashtable hash = new Hashtable(); db = new DBCountry(); try { //获取客户端上传的文件集合 HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; //判断是否存在文件 if (files.Count > 0) { //获取文件集合中的第一个文件(每次只上传一个文件) HttpPostedFile file = files[0]; c_Attach a = new c_Attach(); a.c_ID = Guid.NewGuid().ToString(); string[] str = file.FileName.Split(new char[] { '\\' }); a.c_Name = name; string[] st = str.Last().Split(new char[] { '.' }); a.c_UploadTime = Convert.ToDateTime(DateTime.Now); a.c_Address = "/Upload/ContractSoftEnd/" + a.c_ID + "." + st.Last(); //c_Address是上传文件的相对路径 //将数据存入数据库 db.c_Attach.Add(a); //组合成文件的完整路径 string path = System.Web.HttpContext.Current.Server.MapPath("/Upload/ContractSoftEnd/") + a.c_ID + "." + st.Last(); //保存上传的文件到指定路径中 file.SaveAs(path); db.SaveChanges(); hash.Add("success", true); //hash.Add("c_Name", a.c_Name); // hash.Add("c_Address",a.c_Address); hash.Add("errorMsg", "上传成功"); } else { hash.Add("success", false); hash.Add("errorMsg", "上传失败"); } } catch (Exception ex) { hash.Add("success", false); hash.Add("errorMsg", "上传失败"); } return Json(hash, JsonRequestBehavior.AllowGet); } 下载的话就很简单了,window.open(c_Address);即可,c_Address存储的是文件的相对路径,读取出来打开就可以啦~ 自此,从前台到后台的上传文件并把文件路径存入数据库就到此完成了。有问题希望大家可以指出以便大家一起讨论。
转载请注明原文地址: https://www.6miu.com/read-29299.html

最新回复(0)