前言
此篇讲到的是图片上传功能,每个网站必定会有这样类似的功能,上传文件、上传图片等等。那么接下来,看看我们EF+uploadfile+ftp如何玩转上传图片吧
效果预览
具体实现
一个简单数据库 只有一个主键Id,一个身份证正面路径和一个身份证背面路径三个字段。
首先呢,我们把实体类新建好如下:
public class ImageModel:BaseEntity { /// <summary> /// 用户Id /// </summary> public int ID { get; set; } /// <summary> ///身份证正面相对路径 /// </summary> public string IDProofFront { get; set; } /// <summary> ///身份证背面相对路径 /// </summary> public string IDProofBack { get; set; } }
其中 我们将身份信息实体继承自BaseEntity,我们看看BaseEntity里面是什么东东,代码如下:
public abstract partial class BaseEntity { public override bool Equals(object obj) { return Equals(obj as BaseEntity); } private Type GetUnproxiedType() { return GetType(); } public virtual bool Equals(BaseEntity other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } public static bool operator ==(BaseEntity x, BaseEntity y) { return Equals(x, y); } public static bool operator !=(BaseEntity x, BaseEntity y) { return !(x == y); } }
这里,我们将BaseEntity定义成一个抽象类,里面包含一些静态方法和重载方法
======================回到HTML=======
我们先回过头来讲页面,上面演示的是一个很简单的单页面,HTML代码如下:
<form enctype="multipart/form-data" id="form" action="/Home/UpLoadImage" method="post"> <div class="full_w" style="margin-top: 100px; margin-left: 30%; width: 800px;"> <div class="h_title"> <b>用户上传的文件</b></div> <div class="entry"> 步骤: <span class="red" style="color: red">(上传资料必须是bmp,gif,jpg,jpeg,png类型,不能大于2M)</span> <ol> <li>先按『选择』键选择上传文件;</li> <li>按『上传』键上传文件;</li> <li>按『保存』键保存文件;</li> </ol> </div> <div class="entry"> <div class="sep"></div> </div> <div class="entry"> <div id="wrapper" style="text-align: center; position: relative;"> <div class="form-group"> <input id="uploadfile" type="file" value="浏览..." class="file" name="FileName" data-upload-url="#" style="position: absolute; top: 0; right: 0; min-width: 100%; min-height: 100%; text-align: right; opacity: 0; background: none repeat scroll 0 0 transparent; cursor: inherit; display: block;" /> </div> </div> </div> <table> <tbody> <tr> <td class="entry">身份证正面</td> <td> @if (Model == null || Model.ID == null || string.IsNullOrEmpty(Model.IDProofFront)) { <a href="javascript:void(0);" target="_blank" class="winView"> <img style="border: none; width: 150px; height: 100px" src="/img/noupload.png" /> </a> } else { <a href="@(ViewBag.pathSrc + Model.IDProofFront)" target="_blank"class="winView" > <img style="border: none; width: 150px; height: 100px" src="@(ViewBag.pathSrc + Model.IDProofFront)" /> </a> } @Html.HiddenFor(m => m.IDProofFront) @Html.HiddenFor(m => m.ID) </td> <td> <a href="javascript:void(0)" class="easyui-linkbutton btnFinleUP" data-op="1" data-type="image">上传</a> </td> </tr> <tr> <td class="entry">身份证背面</td> <span id="lblinfosi" style="color: Green"></span> <td> @if (Model == null || Model.ID == null || string.IsNullOrEmpty(Model.IDProofBack)) { <a href="javascript:void(0);" target="_blank" class="winView"> <img style="border: none; width: 150px; height: 100px" src="/img/noupload.png" /> </a> } else { <a href="@(ViewBag.pathSrc + Model.IDProofBack)" target="_blank" class="winView" > <img style="border: none; width: 150px; height: 100px" src="@(ViewBag.pathSrc + Model.IDProofBack)" /> </a> } @Html.HiddenFor(m => m.IDProofBack) </td> <td> <a href="javascript:void(0)" class="easyui-linkbutton btnFinleUP" data-op="2" data-type="image">上传</a> </td> </tr> </tbody> </table> <div class="entry"> <button class="button" name="btnSaveAll" value="保存" id="btnSaveAll" style="height: 30px; width: 80px; text-align: center;">保存</button> <a href="/Home/Index" style="height: 30px; text-align: center; width: 80px; background: #ffffff; border: 1px solid #DCDCDC; border-radius: 2px; color: #444444; cursor: pointer; display: inline-block; font: 700 11px Tahoma, Arial, sans-serif; margin-right: 10px; padding: 7px 12px 7px 12px; position: relative; text-decoration: none; text-shadow: 0px 1px 0px #FFFFFF;">返回</a> </div> </div> </form>
现在我们看页面将会毫无样式,所以我们先引用下样式,这里引用了bootstrap 和一个 style2.css ,引入样式后 界面如下:
其中,关于选择框是用了一个js单独封装起来了,是代码中的zh.js,代码如下:
/*! * FileInput Chinese Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * @author kangqf <kangqingfei@gmail.com> * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['zh'] = { fileSingle: '文件', filePlural: '个文件', browseLabel: '选择 …', removeLabel: '移除', removeTitle: '清除选中文件', cancelLabel: '取消', cancelTitle: '取消进行中的上传', uploadLabel: '上传', uploadTitle: '上传选中文件', msgNo: '没有', msgNoFilesSelected: '', msgCancelled: '取消', msgZoomModalHeading: '详细预览', msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.', msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.', msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ', msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.', msgFileNotFound: '文件 "{name}" 未找到!', msgFileSecured: '安全限制,为了防止读取文件 "{name}".', msgFileNotReadable: '文件 "{name}" 不可读.', msgFilePreviewAborted: '取消 "{name}" 的预览.', msgFilePreviewError: '读取 "{name}" 时出现了一个错误.', msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".', msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.', msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: '该文件上传被中止', msgUploadThreshold: 'Processing...', msgUploadEmpty: 'No valid data available for upload.', msgValidationError: '验证错误', msgLoading: '加载第 {index} 文件 共 {files} …', msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.', msgSelected: '{n} {files} 选中', msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.', msgImageWidthSmall: '宽度的图像文件的"{name}"的必须是至少{size}像素.', msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.', msgImageWidthLarge: '宽度的图像文件"{name}"不能超过{size}像素.', msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.', msgImageResizeError: '无法获取的图像尺寸调整。', msgImageResizeException: '错误而调整图像大小。<pre>{errors}</pre>', msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!', msgAjaxProgressError: '{operation} failed', ajaxOperations: { deleteThumb: 'file delete', uploadThumb: 'single file upload', uploadBatch: 'batch file upload', uploadExtra: 'form data upload' }, dropZoneTitle: '拖拽文件到这里 …<br>支持多文件同时上传', dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)', fileActionSettings: { removeTitle: '删除文件', uploadTitle: '上传文件', zoomTitle: '查看详情', dragTitle: '移动 / 重置', indicatorNewTitle: '没有上传', indicatorSuccessTitle: '上传', indicatorErrorTitle: '上传错误', indicatorLoadingTitle: '上传 ...' }, previewZoomButtonTitles: { prev: '预览上一个文件', next: '预览下一个文件', toggleheader: '缩放', fullscreen: '全屏', borderless: '无边界模式', close: '关闭当前预览' } }; })(window.jQuery);