如何在asp.net中使用jquery将文件上传到文件夹?

时间:2013-11-13 16:00:21

标签: javascript asp.net

我尝试使用asp.net中的jquery ajax文件上传脚本将文件上传到文件夹。我显示自定义文件上传图像而不是文件上传控件。这种方法在firefox和chrome中运行良好。但在IE中它不起作用。我的代码如下:

<img src="Images/attach.png" title="Add Attachment" style="vertical-align: middle; height:24px;cursor:pointer; " onclick="document.getElementById('fileToUpload').click();" id="attach" alt=""/>&nbsp;<img src="images/ajax-loader.gif" style="height:24px;vertical-align: middle;display:none;" id="noteloading" alt=""/> <asp:FileUpload ID="fileToUpload" runat="server" style="display:none;" ClientIDMode="Static" onchange="getFileName()" />
 <input type="button" value="Submit" onclick="ajaxFileUpload()" />

脚本:

 function ajaxFileUpload()
{

 var fileName = $('#<%=fileToUpload.ClientID %>').val().replace(/.*(\/|\\)/, '');
              var user = '<%= User.Identity.Name%>';
              $('#NotesStatus').val('');
              $(obj).hide();
              if (fileName != "" && fileName != null) {

                  $.ajaxFileUpload({ url: 'AjaxFileUploader.ashx',
                      secureuri: false,
                      fileElementId: 'fileToUpload',
                      dataType: 'json',
                      success: function (data, status) {
                          if (typeof (data.error) != 'undefined') {
                              if (data.error != '') {
                                  alert(data.error);
                              } else {
                                  SaveNotesData(entryId, formId, user, action, comments, actDate, relatedData, data.msg);
                              }
                          }
                      },
                      error: function (data, status, e) {
                          alert(e);
                          alert('hai');
                      }
                  });

              }
              else {
                  SaveNotesData(entryId, formId, user, action, comments, actDate, relatedData, fileName);
              }
}
function SaveNotesData(entryId, formId, user, action, comments, actDate, relatedData, fileName)
{
         $.ajax({ url: "AjaxService.asmx/AddEntryNotes", contentType: "application/json; charset=utf-8", type: "POST",
                data: '{"entryid":' + entryId + ', "frmid":"' + formId + '","user":"<%= User.Identity.Name%>","action":"' + action + '","comments":"' + comments + '","actDate":"' + actDate + '", "relatedData":"'+relatedData+'", "fileName":"' + fileName + '"}',
                success: function (result) { $('#imgprogressing').hide();
                    if (result == null || result.d == null) return;
                    if (result.d == "true")
                    {
                        $('#NotesStatus').append("Notes Added Successfully");
                        $('.usernotes').load("NotesPopup.aspx?formId=" + encodeURI(formId) + "&entryId=" + encodeURI(entryId) + "&uid="+(new Date()).getTime());

                        $('.toolTip').each(function (index) {
                            attachNotes($(this).attr("entryid"), $(this).attr("frm"), $(this));
                        });

                        $('#<%=divAddNote.ClientID %>').dialog('close');



                    }
                    else
                    {
                        alert("Failure in Notes Addition !");
                    }
                    //getNotes(entryId, formId, $('.usernotes'));
                    //HideNotesPopup();
                    document.getElementById('hlNoteSubmit').style.visibility = 'visible';
                    $('#NotesStatus').html(''); $('#<%=taComments.ClientID %>').val('');
                    $('#<%= actionDate.ClientID %>').val($.datepicker.formatDate('m/d/yy', new Date()));
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { $('#imgprogressing').hide(); alert('Loading failed!!'); }
            });
}

AjaxFileUploader.ashx:

 if (context.Request.Files.Count > 0)
        {
            string path = context.Server.MapPath("~/Uploads");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            var file = context.Request.Files[0];

            string fileName;

            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
            {
                string[] files = file.FileName.Split(new char[] { '\\' });
                fileName = files[files.Length - 1];
            }
            else
            {
                fileName = file.FileName;
            }
            string newFilename = Guid.NewGuid().ToString();
            FileInfo fInfo = new FileInfo(fileName);
            newFilename = string.Format("{0}{1}", newFilename, fInfo.Extension);
            string strFileName = newFilename;
            fileName = Path.Combine(path, newFilename);
            file.SaveAs(fileName);


            string msg = "{";
            msg += string.Format("error:'{0}',\n", string.Empty);
            msg += string.Format("msg:'{0}'\n", strFileName);
            msg += "}";
            context.Response.Write(msg);


        }

当我显示文件上传控件并浏览文件上传控件时,它正在工作即没有问题。而不是当我设置filupload控件显示无和触发fileupload点击通过自定义图像点击不是所有工作在ie。但是在firefox和chrome上运行良好。如何解决?

1 个答案:

答案 0 :(得分:0)

<div style="position:relative;display:inline-block;left:-4px;bottom:-6px;width:16px;  height: 24px;overflow:hidden;">
<img src="/images/attach.jpg" alt="" title="Add Attachment" style="height:24px;width:16px; position: relative;top: 1px; left: 0px;"/>
<input type="file" id="fileupload" name="upload" onchange="getFileName();" style=" opacity: 0;font-size: 50px;width:16px; filter:alpha(opacity: 0);  position: relative; top: -22px; left: -1px" />
</div>

如需进一步参考,请参阅此内容。 In JavaScript can I make a "click" event fire programmatically for a file input element?

演示:

http://jsfiddle.net/k6zBQ/2/