bootstrap图片上传功能

重点:

  fileupload    、loadImage

 

引用js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
      <!-- Bootstrap CSS -->
    <link href="~/lib/bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet" type="text/css" />
    <!-- Bootstrap CSS -->
    <link href="~/lib/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
 
     <!-- Bootstrap styles
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> -->
<!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
<link href="~/lib/jquery-file-upload/9.21.0/css/jquery.fileupload.css" rel="stylesheet" />
 
    <!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
    <script src="~/lib/jquery-file-upload/9.21.0/js/vendor/jquery.ui.widget.js"></script>
    <!-- The Load Image plugin is included for the preview images and image resizing functionality -->
    <script src="~/lib/javascript-load-image/2.19.0/js/load-image.all.min.js"></script>
    <script src="~/lib/javascript-canvas-to-blob/3.14.0/js/canvas-to-blob.js"></script>
    <!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
    <script src="~/lib/jquery-file-upload/9.21.0/js/jquery.iframe-transport.js"></script>
    <!-- The basic File Upload plugin -->
    <script src="~/lib/jquery-file-upload/9.21.0/js/jquery.fileupload.js"></script>
    <!-- The File Upload processing plugin -->
    <script src="~/lib/jquery-file-upload/9.21.0/js/jquery.fileupload-process.js"></script>
    <!-- The File Upload image preview & resize plugin -->
    <script src="~/lib/jquery-file-upload/9.21.0/js/jquery.fileupload-image.js"></script>
    <!-- The File Upload validation plugin -->
    <script src="~/lib/jquery-file-upload/9.21.0/js/jquery.fileupload-validate.js"></script>
    <script src="~/js/EnterpriseDetail.js?v=1"></script>
    <script type="text/javascript" src="~/lib/jquery-validation/1.17.0/jquery.validate.js"></script>
    <script type="text/javascript" src="~/lib/jquery-validation-unobtrusive/3.2.9/jquery.validate.unobtrusive.js"></script>
    <script type="text/javascript" src="~/lib/jquery-validation/1.17.0/localization/messages_zh.js" charset="utf-8"></script

  

页面html

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
         <div class="form-group row">
                <label class="col-md-2 col-form-label ">营业执照*</label>
                <div class="col-md-6">
                    <!-- The fileinput-button span is used to style the file input field as button -->
                    <button id="upload_bt1" type="button" class="fileinput-button btn btn-info waves-effect waves-light mr-4">上传附件</button>
                    <button id="remove_bt1" type="button" class="ImgRemove-button btn btn-info waves-effect waves-light mr-4" style="display:none">删除附件</button>
                    <!-- The global progress bar -->
                    <div id="upload_progress1" class="progress" style="display:none">
                        <div class="progress-bar progress-bar-success"></div>
                    </div>
                    <!-- The container for the uploaded files -->
                    <div id="upload_show1" class="files "></div>
                    <input asp-for="BusinessLicence" type="text" style="display:none" class="imageGroupId">
                    <span asp-validation-for="BusinessLicence" class="text-danger validationShow"></span>
                </div>
            </div>
 
 
 
 
 
 
 
 
<form asp-controller="upload" asp-action="image" method="post" id="uploadForm">
    <!-- The file input field used as target for the file upload widget -->
    <input id="fileupload" type="file" name="files[]" multiple>
    <div class="uploadInfo">
 
    </div>
</form>

  

 

页面 js实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
ImageUpload.Init("@Url.Content("~/upload/image")");
ImageLoad.Init(100, 100, 50, 50, true);
 
 
 
 
 
var ImageUpload = {
    imageUrl:"",
    Init:function(urlV){
        ImageUpload.imageUrl=urlV
        ImageUpload.AddEvent();
        ImageUpload.OperateInjecte();
    },
    AddEvent: function () {
         $(".fileinput-button").click(function () {
            var $this = $(this);
            var $fileupload = $('#fileupload');
            var $showDiv = $this.siblings(".files:first");
            var $progress = $this.siblings(".progress:first");
            var $removeBt = $this.siblings(".ImgRemove-button:first");
            var $groupGuidInput=$this.siblings(".imageGroupId:first");
 
            var $fileuploadInfo = $fileupload.siblings(".uploadInfo:first");
            $fileuploadInfo.append('<input class="uploadPart'+
                '" attr-bt="' + $this.attr("id") +
                '" attr-removeBt="' + $removeBt.attr("id") +
                '" attr-show="' + $showDiv.attr("id") + '" ' +
                '" attr-progress="' + $progress.attr("id") +
                '" attr-groupGuidInput="' + $groupGuidInput.attr("id") +
                '" attr-groupId="" type="hidden">');
             $fileupload.click();
              
        });
        $(".ImgRemove-button").click(function () {
            var $this = $(this);
            var $showDiv = $this.siblings(".files:first");
            var $uploadBt = $this.siblings(".fileinput-button:first");
            var $groupGuid=$this.siblings(".imageGroupId:first");
            $showDiv.html("");
            $groupGuid.val("");
            $this.hide();
            $uploadBt.show();
        });
    },
    SetImgFromGroupGuid:function(edit){
         $(".imageGroupId").each(function () {
            var $this = $(this);
            var $fileupload = $('#fileupload');
            var $showDiv = $this.siblings(".files:first");
            var $progress = $this.siblings(".progress:first");
            var $removeBt = $this.siblings(".ImgRemove-button:first");
            var $uploadBt=$this.siblings(".fileinput-button:first");
 
            var $fileuploadInfo = $fileupload.siblings(".uploadInfo:first");
            var $node= $('<div/>').appendTo($showDiv);
            var getUrl=ImageUpload.imageUrl+"?g="+$this.val()+"&j=false";
 
            ImageLoad.loadUrlImageToPriview(getUrl,function($img){
                if(edit){
                    $uploadBt.hide();
                    $removeBt.show();
                }else{
                    $uploadBt.hide();
                    $removeBt.hide();
                }
                $node.prepend($img);
                var $node2=$('<p/>')
                    .append($('<a href="'+getUrl+'"  target="_blank" class="pull-left py-2"/>').text("查看附件"));
                $node2.appendTo($node);
            });    
        });
    },
    OperateInjecte:function () {
          $('#fileupload').fileupload({
            url:ImageUpload.imageUrl ,
            dataType: 'json',
            autoUpload: false,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            maxFileSize: 999000,
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator.userAgent),
            previewMaxWidth: 100,
            previewMaxHeight: 100,
            previewCrop: true,
        })
            .on('fileuploadadd', function (e, data) {
                var $uploadInfo = $('#fileupload').siblings(".uploadInfo");
                var $uploadInfoParts = $uploadInfo.children(".uploadPart:last")
                var showDivId = $uploadInfoParts.attr("attr-show");
                var progressId = $uploadInfoParts.attr("attr-progress");
                var uploadBt= $uploadInfoParts.attr("attr-bt");
                var removeBt= $uploadInfoParts.attr("attr-removeBt");
                var groupGuidInput= $uploadInfoParts.attr("attr-groupGuidInput");
                var $showDiv = $('#' + showDivId);
                var $progress = $('#' + progressId);
                var $uploadBt = $('#' + uploadBt);
                var $removeBt = $('#' + removeBt);
                var $groupGuidInput = $('#' + groupGuidInput);
                $progress.show();
                data.context = $('<div/>').appendTo($showDiv);
                data.uploadBt = $uploadBt;
                data.uploadBt.attr("disabled", "disabled")
                data.removeBt=$removeBt;
                data.groupGuidInput=$groupGuidInput;
                $.each(data.files, function (index, file) {
                    var uploadErrors = [];
                    if (file['size'] > 20971520) {
                        uploadErrors.push('文件不能大于20M');
                    }
                    var acceptFileTypes = /(\.|\/)?(gif|jpe?g|png|pdf|vnd\.openxmlformats|application\/msword|application\/vnd\.openxmlformats\-officedocument\.wordprocessingml\.document|application\/vnd\.ms\-excel|application\/vnd\.openxmlformats\-officedocument\.spreadsheetml\.sheet)$/i;
                    if (!acceptFileTypes.test(file['type'])) {
                        uploadErrors.push('文件类型不正确,请上传图片、pdf、word、excel文件');
                    }
                    if (uploadErrors.length > 0) {
                        node = $('<p/>')
                            .append($('<span class="text-danger"/>').text(uploadErrors.join("\n")));
                        node.appendTo(data.context);
                        return;
                    }
                    $progress.show();
                    data.submit()
                        .always(function () {
                            $progress.hide();
                            data.uploadBt.removeAttr("disabled");
                            if (!index) {
                                node = $('<p/>')
                                node.appendTo(data.context);
                            }
                        });
                });
            })
            .on('fileuploadprocessalways', function (e, data) {
                var index = data.index,
                file = data.files[index],
                $node = $(data.context);
                if (file.preview) {
                    ImageLoad.loadFileImageToPriview(file, function($img){
                        $node.prepend($img);
                    });
                }
                if (file.error) {
                   //node.append($('<p/>'))
                       // .append($('<span />').text("非图片类型,无缩略图!"));
                }
            })
            .on('fileuploadprogressall', function (e, data) {
                var $uploadInfo = $('#fileupload').siblings(".uploadInfo");
                var $uploadInfoParts = $uploadInfo.children(".uploadPart:last")
                var progressId = $uploadInfoParts.attr("attr-progress");
                var $progress = $('#' + progressId);
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $progress.find(' .progress-bar').css(
                    'width',
                    progress + '%'
                );
            })
            .on('fileuploaddone', function (e, data) {
                node = $('<p/>');
                file = data.files[0];
                var $fileupload = $('#fileupload');
                var $fileuploadInfo = $fileupload.siblings(".uploadInfo:first");
                var $fileuploadInfoTarget = $fileuploadInfo.children("input:last");
                 
                if (data.result) {
                    var groupId = data.result[0].groupID;
                    $fileuploadInfoTarget.attr("attr-groupId", groupId);
                    data.groupGuidInput.val(groupId).trigger("change");
                    data.uploadBt.hide();
                    data.removeBt.show();
                    node
                        .append($('<a href="'+ImageUpload.imageUrl+'?g='+groupId+'&j=false"  target="_blank" class="pull-left py-2"/>').text(file.name+":上传成功"));
                }
                else {
                    data.uploadBt.show();
                    data.groupGuidInput.val("").trigger("change");
                    node
                        .append($('<span class="text-danger"/>').text(file.name +':上传失败'));
                }
                node.appendTo(data.context);
            })
            .on('fileuploadfail', function (e, data) {
                file = data.files[0];
                node = $('<p/>')
                    .append($('<span class="text-danger"/>').text(file.name +':上传失败'));
                node.appendTo($(data.context));
            })
            .prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    }
}
 
var ImageLoad = {
    Init:function(maxWidth,maxHeight,minWidth,minHeight,canvas){
        ImageLoad.maxWidth=maxWidth;
        ImageLoad.maxHeight=maxHeight;
        ImageLoad.minWidth=minWidth;
        ImageLoad.minHeight=minHeight;
        ImageLoad.canvas=canvas;
    },
    maxWidth:100,
    maxHeight:100,
    minWidth:50,
    minHeight:50,
    canvas:true,
    loadUrlImageToPriview: function (url,callback)
    {
        loadImage(
            url,
            function (img) {
                 if (typeof (callback) === "function") {
                        callback($(img));
                 }
                 
            },
            {
                maxWidth:  ImageLoad.maxWidth,
                maxHeight: ImageLoad.maxHeight,
                minWidth: ImageLoad.minWidth,
                minHeight: ImageLoad.minHeight,
                canvas: ImageLoad.canvas
            }
        );
    },
    loadFileImageToPriview: function (file,callback) {
        loadImage(
            file,
            function (img) {
                if (typeof (callback) === "function") {
                        callback($(img));
                 }
            },
            {
                maxWidth:  ImageLoad.maxWidth,
                maxHeight: ImageLoad.maxHeight,
                minWidth: ImageLoad.minWidth,
                minHeight: ImageLoad.minHeight,
                canvas: ImageLoad.canvas
            }
        );
    },
    blobToFile: function (file, $node)
    {
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
    }
}

  

 

posted @   PanPan003  阅读(3179)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示