首页 新闻 赞助 找找看

Jquery File UpLoad上传文件后前台显示异常

0
悬赏园豆:30 [已解决问题] 解决于 2015-05-25 11:25

项目中用到Jquery File UpLoad实现多文件上传,上传到后台是可以实现,但前台就是不能实现喔想要的效果,各位,能帮忙看看是什么原因吗?

前台代码如下:

  1 <!-- summernote plugin styles -->
  2 <link href="/Content/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
  3 <link rel="stylesheet" href="/Content/@code/js/general/summernote/summernote.css" />
  4 <!-- summernote js -->
  5 <script type="text/javascript" src="/Content/@code/js/general/summernote/summernote.js"></script>
  6 <script type="text/javascript" src="/Content/@code/js/general/summernote/lang/summernote-zh-CN"></script>
  7 
  8 <script type="text/javascript" src="/Content/@code/js/pages/platform-release-local.js"></script>
  9 <link href="/Content/@code/js/general/jquery-file-upload/css/jquery.fileupload-ui.css" rel="stylesheet" />
 10 <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
 11 <script id="template-upload" type="text/x-tmpl">
 12       {% for (var i=0, file; file=o.files[i]; i++) { %}
 13           <tr class="template-upload fade">
 14               <td>
 15                   <span class="preview"></span>
 16               </td>
 17               <td>
 18                   <p class="name">{%=file.name%}</p>
 19                   <!--{% if (file.error) { %}
 20                       <div><span class="label label-danger">Error</span> {%=file.error%}</div>
 21                   {% } %}-->
 22                   <!--隐藏此段-->
 23               </td>
 24               <td>
 25                   <p class="size">{%=o.formatFileSize(file.size)%}</p>
 26                   <!--{% if (!o.files.error) { %}
 27                       <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-
 28 
 29 valuemax="100" aria-valuenow="0">
 30                       <div class="progress-bar progress-bar-success" style="width:0%;"></div>
 31                       </div>
 32                   {% } %}-->
 33                   <!--隐藏此段-->
 34               </td>
 35               <td>
 36                   {% if (!o.files.error && !i && !o.options.autoUpload) { %}
 37                       <button class="btn blue start">
 38                           <i class="icons-upload"></i>
 39                           <span>开始上传</span>
 40                       </button>
 41                   {% } %}
 42                   {% if (!i) { %}
 43                       <button class="btn red cancel">
 44                           <i class="icons-ban-circle"></i>
 45                           <span>取消</span>
 46                       </button>
 47                   {% } %}
 48               </td>
 49           </tr>
 50       {% } %}
 51 </script>
 52 <!-- The template to display files available for download -->
 53 <script id="template-download" type="text/x-tmpl">
 54       {% for (var i=0, file; file=o.files[i]; i++) { %}
 55           <tr class="template-download fade">
 56               <td>
 57                   <span class="preview">
 58                       {% if (file.thumbnailUrl) { %}
 59                           <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img 
 60 
 61 src="{%=file.thumbnailUrl%}"></a>
 62                       {% } %}
 63                   </span>
 64               </td>
 65               <td>
 66                   <p class="name">
 67                       {% if (file.url) { %}
 68                           <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" 
 69 
 70 {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
 71                       {% } else { %}
 72                           <span>{%=file.name%}</span>
 73                       {% } %}
 74                   </p>
 75                  <!-- {% if (file.error) { %}
 76                       <div><span class="label label-danger">Error</span> {%=file.error%}</div>
 77                   {% } %}-->
 78                   <!--隐藏此段-->
 79               </td>
 80               <td>
 81                   <span class="size">{%=o.formatFileSize(file.size)%}</span>
 82               </td>
 83               <td>
 84                   {% if (file.deleteUrl) { %}
 85                       <button class="btn red delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if 
 86 
 87 (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
 88                           <i class="icons-trash"></i>
 89                           <span>删除</span>
 90                       </button>
 91                       <input type="checkbox" name="delete" value="1" class="toggle">
 92                   {% } else { %}
 93                       <button class="btn yellow cancel">
 94                           <i class="icons-ban-circle"></i>
 95                           <span>取消</span>
 96                       </button>
 97                   {% } %}
 98               </td>
 99           </tr>
100       {% } %}
101 </script>
102 
103 <!-- BEGIN CORE PLUGINS -->
104 <script src="/Content/@code/js/general/jquery-file-upload/js/vendor/jquery.ui.widget.js"></script>
105 <script src="/Content/@code/js/general/jquery-file-upload/js/vendor/tmpl.min.js"></script>
106 <!-- The Load Image plugin is included for the preview images and image resizing functionality -->
107 <script src="/Content/@code/js/general/jquery-file-upload/js/vendor/load-image.min.js"></script>
108 <!-- The Canvas to Blob plugin is included for image resizing functionality -->
109 <script src="/Content/@code/js/general/jquery-file-upload/js/vendor/canvas-to-blob.min.js"></script>
110 <!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
111 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.iframe-transport.js"></script>
112 <!-- The basic File Upload plugin -->
113 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload.js"></script>
114 <!-- The File Upload processing plugin -->
115 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload-process.js"></script>
116 <!-- The File Upload image preview & resize plugin -->
117 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload-image.js"></script>
118 <!-- The File Upload audio preview plugin -->
119 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload-audio.js"></script>
120 <!-- The File Upload video preview plugin -->
121 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload-video.js"></script>
122 <!-- The File Upload validation plugin -->
123 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload-validate.js"></script>
124 <!-- The File Upload user interface plugin -->
125 <script src="/Content/@code/js/general/jquery-file-upload/js/jquery.fileupload-ui.js"></script>
126 
127 <script src="/Content/tongji/js/pages/form-fileupload.js"></script>
128 <h3 class="page-title">发布信息<small><a href="javascript:;" class="backbtn"> 信息发布管理</a></small></h3>
129 <a href="javascript:;" class="pull-right backbtn">< 返回</a>
130 <div class="content">
131     <div class="clearfix"></div>
132     <div class="portlet box">
133         <form id="AddContentForm" method="post" action="/Backend/Notification/SaveContent" enctype="multipart/form-data"
134             class="form-horizontal">
135             <div class="form-group">
136                 <label for="" class="col-md-3 control-label"><span class="red">*</span>信息标题:</label>
137                 <div class="col-md-4">
138                     <input type="text" value="" class="form-control" id="Title" name="Title">
139                 </div>
140                 <div class="col-md-3">
141                     <span class="back"></span>
142                 </div>
143             </div>
144             <div class="form-group">
145                 <label for="" class="col-md-3 control-label"><span class="red">*</span>所属栏目:</label>
146                 <div class="col-md-2">
147                     <select name="ParCateID" id="ParCateID" onchange="ChangeCateContent()" class="form-control width-auto">
148                         <option value="">请选择父栏目</option>
149                         @foreach (var c in list)
150                         { 
151                             <option value="@c.ID">@c.Name</option>
152                         }
153                     </select>
154                 </div>
155                 <div class="col-md-3">
156                     <select name="CategoryID" id="CategoryID" class="form-control width-auto">
157                         <option value="">请选择栏目</option>
158                     </select>
159                 </div>
160                 <div class="col-md-3">
161                     <span class="back"></span>
162                 </div>
163             </div>
164             <div class="form-group">
165                 <label class="col-md-3 control-label" for=""><span class="red">*</span>发布者:</label>
166                 <div class="col-md-4">
167                     <input type="text" value="" class="form-control" id="Publisher" name="Publisher">
168                 </div>
169                 <div class="col-md-3">
170                     <span class="back"></span>
171                 </div>
172             </div>
173             <div class="form-group form-group-width">
174                 <label class="col-md-3 control-label" for="">有效期:</label>
175                 <div class="col-md-8">
176                     <div class="input-daterange input-group">
177                         <div class="input-group-addon">
178                             <i class="icons-calendar"></i>
179                         </div>
180                         <input type="text" class="input-sm form-control" id="ExpiryDate" name="ExpiryDate" />
181                     </div>
182                     <div class="help-block">
183                         <label class="middle">
184                             <input class="ace" type="checkbox" id="IsNeverExpiry" value="true" name="IsNeverExpiry" />
185                             <span class="lbl padding-4">永久有效</span>
186                         </label>
187                     </div>
188                 </div>
189             </div>
190             <div class="form-group">
191                 <label class="col-md-3 control-label" for="">是否显示:</label>
192                 <div class="col-md-9">
193                     <div class="radio-inline">
194                         <label>
195                             <input name="IsDisplay" value="true" class="ace" type="radio" checked /><span for="IsDisplay"
196                                 class="lbl padding-8" name="IsDisplay">是</span>
197                         </label>
198                         <label>
199                             <input name="IsDisplay" value="false" class="ace" type="radio" /><span for="IsDisplay"
200                                 class="lbl padding-8" name="IsDisplay">否</span>
201                         </label>
202                     </div>
203                 </div>
204             </div>
205             <div class="form-group">
206                 <label class="col-md-3 control-label" for="">发布机构:</label>
207                 <div class="col-md-4">
208                     <input type="text" value="" class="form-control" id="PublishDept" name="PublishDept">
209                 </div>
210             </div>
211             <div class="form-group">
212                 <label class="col-md-3 control-label" for="">附件:</label>
213                 <div class="col-md-8">
214                     <form action="/">
215                         <div id="fileupload">
216                             <div class="row fileupload-buttonbar">
217                                 <div class="col-lg-7">
218                                     <span class="btn green fileinput-button">
219                                         <i class="icons-plus"></i>
220                                         <span>添加附件</span>
221                                         <input type="file" name="files[]" multiple>
222                                     </span>
223                                     <button type="submit" class="btn blue start">
224                                         <i class="icons-upload"></i>
225                                         <span>开始上传</span>
226                                     </button>
227                                     <button type="reset" class="btn yellow cancel">
228                                         <i class="icons-ban-circle"></i>
229                                         <span>取消</span>
230                                     </button>
231                                     <span class="fileupload-loading"></span>
232                                 </div>
233                                 <div class="col-lg-5 fileupload-progress fade">
234                                     <div class="progress progress-striped active" role="progressbar" aria-valuemin="0"
235                                         aria-valuemax="100">
236                                         <div class="progress-bar progress-bar-success" style="width: 0%;"></div>
237                                     </div>
238                                     <div class="progress-extended">&nbsp;</div>
239                                 </div>
240                             </div>
241                             <table role="presentation" class="table table-striped table-upload clearfix">
242                                 <tbody class="files"></tbody>
243                             </table>
244                         </div>
245                     </form>
246                 </div>
247             </div>
248             <div class="form-group">
249                 <label class="col-md-3 control-label" for=""><span class="red">*</span>内容:</label>
250                 <div class="col-md-8">
251                     <textarea class="summernote" id="Context" name="Context" style="resize: none; width: 630px; height: 190px;"></textarea>
252                 </div>
253                 <div class="col-md-3">
254                     <span class="back"></span>
255                 </div>
256             </div>
257             <div class="clearfix form-actions fluid">
258                 <div class="col-md-offset-3 col-md-8">
259                     <button class="btn btn-lg btn-default btn-primary blue" id="submitBtn" type="button">
260                         保存
261                     </button>
262                     <button class="btn btn-lg btn-default btn-primary default" id="cancelBtn">
263                         取消
264                     </button>
265                 </div>
266             </div>
267         </form>
268     </div>
269 </div>

Jquery file UpLoad初始化代码如下:

 1 var FormFileUpload = function () {
 2 
 3 
 4     return {
 5         //main function to initiate the module
 6         init: function () {
 7 
 8              // Initialize the jQuery File Upload widget:
 9             $('#fileupload').fileupload({
10                 // Uncomment the following to send cross-domain cookies:
11                 //xhrFields: {withCredentials: true},                
12                 url: '/Backend/Notification/UpLoadFiles'
13             });
14 
15             // Enable iframe cross-domain access via redirect option:
16             $('#fileupload').fileupload(
17                 'option',
18                 'redirect',
19                 window.location.href.replace(
20                     /\/[^\/]*$/,
21                     '/cors/result.html?%s'
22                 )
23             );
24 
25             // Demo settings:
26             $('#fileupload').fileupload('option', {
27                 url: $('#fileupload').fileupload('option', 'url'),
28                 // Enable image resizing, except for Android and Opera,
29                 // which actually support image resizing, but fail to
30                 // send Blob objects via XHR requests:
31                 disableImageResize: /Android(?!.*Chrome)|Opera/
32                     .test(window.navigator.userAgent),
33                 maxFileSize: 5000000,//最大上传5M
34                 //此处隐藏表示不限制可上传类型
35                // acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
36             });
37 
38                 // Upload server status check for browsers with CORS support:
39             /*if ($.support.cors) {
40                 $.ajax({
41                     url: 'assets/plugins/jquery-file-upload/server/php/',
42                     type: 'HEAD'
43                 }).fail(function () {
44                     $('<div class="alert alert-danger"/>')
45                         .text('Upload server currently unavailable - ' +
46                                 new Date())
47                         .appendTo('#fileupload');
48                 });
49             }*/
50             
51             ////////////////////
52 
53             // Initialize the jQuery File Upload widget:
54             $('#fileupload').fileupload({
55                 // Uncomment the following to send cross-domain cookies:
56                 //xhrFields: {withCredentials: true},
57                 autoUpload: false,
58                 url: '/Backend/Notification/UpLoadFiles'
59             });
60 
61             // initialize uniform checkboxes  
62             
63             //隐藏checkbox
64             // App.initUniform('.fileupload-toggle-checkbox');
65         }
66 
67     };
68 
69 }();

后台保存文件代码如下:

 #region 文件上传

        private string StorageRoot
        {
            get { return Path.Combine(Server.MapPath("~/Files/" + this.OrgCode + "/" + this.SysCode + "/Attachment/")); }
        }

        //DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS
        [HttpGet]
        public void Delete(string id)
        {
            var filename = id;
            var filePath = Path.Combine(Server.MapPath("~/Files"), filename);

            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
            }
        }

        //DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS
        [HttpGet]
        public void Download(string id)
        {
            var filename = id;
            var filePath = Path.Combine(Server.MapPath("~/Files"), filename);

            var context = HttpContext;

            if (System.IO.File.Exists(filePath))
            {
                context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                context.Response.ContentType = "application/octet-stream";
                context.Response.ClearContent();
                context.Response.WriteFile(filePath);
            }
            else
                context.Response.StatusCode = 404;
        }

        //DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS
        [HttpPost]
        public ActionResult UploadFiles()
        {
            var r = new List<ViewDataUploadFilesResult>();

            foreach (string file in Request.Files)
            {
                var statuses = new List<ViewDataUploadFilesResult>();
                var headers = Request.Headers;

                if (string.IsNullOrEmpty(headers["X-File-Name"]))
                {
                    UploadWholeFile(Request, statuses);
                }
                else
                {
                    UploadPartialFile(headers["X-File-Name"], Request, statuses);
                }

                JsonResult result = Json(statuses);
                result.ContentType = "text/plain";

                return result;
            }

            return Json(r);
        }

        private string EncodeFile(string fileName)
        {
            return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName));
        }

        private void UploadPartialFile(string fileName, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
            var file = request.Files[0];
            var inputStream = file.InputStream;

            var fullName = Path.Combine(StorageRoot, Path.GetFileName(fileName));

            using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
            {
                var buffer = new byte[1024];

                var l = inputStream.Read(buffer, 0, 1024);
                while (l > 0)
                {
                    fs.Write(buffer, 0, l);
                    l = inputStream.Read(buffer, 0, 1024);
                }
                fs.Flush();
                fs.Close();
            }
            statuses.Add(new ViewDataUploadFilesResult()
            {
                name = fileName,
                size = file.ContentLength,
                type = file.ContentType,
                url = StorageRoot + fileName,
                delete_url = "/" + this.OrgCode + "/" + this.SysCode + "/Attachment/" + fileName,
                thumbnail_url = @"data:image/png;base64," + EncodeFile(fullName),
                delete_type = "GET",
            });
        }

        private void UploadWholeFile(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            for (int i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];

                var fullPath = Path.Combine(StorageRoot, Path.GetFileName(file.FileName));

                if (!Directory.Exists(StorageRoot))
                    Directory.CreateDirectory(StorageRoot);
                file.SaveAs(fullPath);
                statuses.Add(new ViewDataUploadFilesResult()
                {
                    name = file.FileName,
                    size = file.ContentLength,
                    type = file.ContentType,
                    url = "/" + this.OrgCode + "/" + this.SysCode + "/Attachment/" + file.FileName,
                    // url = "/Home/Download/" + file.FileName,
                    delete_url = "/" + this.OrgCode + "/" + this.SysCode + "/Attachment/" + file.FileName,
                    thumbnail_url = @"data:image/png;base64," + EncodeFile(fullPath),
                    delete_type = "GET",
                });
            }
        }

        #endregion

文件能上传成功,但现实效果如下:

 

我想要实现的效果如下:

 

各位能帮忙看下是哪个地方出现问题了。补充下:通过FF能看到返回的结果:页面上就是不显示,还请各位大牛能帮忙看看是哪个地方的问题。。

mczxmin的主页 mczxmin | 初学一级 | 园豆:196
提问于:2015-03-20 18:54
< >
分享
最佳答案
0

换了写法,问题解决了。

mczxmin | 初学一级 |园豆:196 | 2015-05-25 11:24

大哥:你的代码我可以看看嘛,这个插件的资料网上有限。谢谢

天水围的世界 | 园豆:200 (初学一级) | 2015-09-11 12:00

 我的QQ 1010427151

天水围的世界 | 园豆:200 (初学一级) | 2015-09-11 12:00

大哥,怎么改呀,能分享下么

任意球 | 园豆:107 (初学一级) | 2016-06-27 11:26
其他回答(1)
0

既然有结果,没显示,那么就断点一下用于显示的那个函数,调试下吧。

收获园豆:30
幻天芒 | 园豆:37175 (高人七级) | 2015-03-21 09:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册