客户端JS上传文件

在页面 :
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<table>
<tr>
      <td>相关上传:</td>
                     <td>
                         <div style="display:none;" id="theFile"><div>
                 附件: <input type="file" name="file" />
                 描述: <input type="text" name="file_desc" />
               <a href="###">[删除]</a> <a href="javascript:attach_add();">[增加]</a></div>
                  </div>
                   <div id="myFile">
                   </div>
                     </td>
</tr>
</table>
</form>
<script type="text/javascript">
        var aid = 1;
        function attach_add(){
         var newNode = document.getElementById('theFile').firstChild.cloneNode(true);
         newNode.id = "file" + aid;
         newNode.childNodes[1].name = "file_" +aid;
         newNode.childNodes[3].name = "filedesc_" +aid;
         newNode.childNodes[5].href = "javascript:attach_sub(" +aid+ ")";
         document.getElementById('myFile').appendChild(newNode);
         aid++;
        }
        attach_add();
        function attach_sub(id){
         var theNode = document.getElementById('file'+id);
         
         document.getElementById('myFile').removeChild(theNode);
        }
</script>
后台代码:

public class FileUpload {
  private static string _fileType = ".zip|.rar|.txt";
  private static string _uploadPath = "UploadFiles/";
  private static int _maxFilesQuantity = 10;

  public static string FileType {
   get { return _fileType; }
   set { _fileType = value; }
  }

  public static string UploadPath {
   get { return _uploadPath + DateTime.Now.ToString("yyyy_MM") + "/"; }
   set { _uploadPath = value; }
  }

  public static int MaxFilesQuantity {
   get { return _maxFilesQuantity; }
   set { _maxFilesQuantity = value; }
  }


  /// <summary>
  /// Upload
  /// </summary>
  /// <param name="grade">CategoryId</param>
  /// <param name="gradeid">ItemId</param>
  public static void Save(int grade, int gradeid) {
   HttpFileCollection files = HttpContext.Current.Request.Files;
   if (files.Count > 0 && files.Count <= _maxFilesQuantity) {
    for (int i = 0; i < files.Count; i++) {
     HttpPostedFile file = files[i];
     if (file.ContentLength > 0) {
      string fileName = GenerateFileName(System.IO.Path.GetFileName(file.FileName));
      string uploadPath = UploadPath;
      string filePath = HttpContext.Current.Server.MapPath("/"+uploadPath);

      if (CheckExtensionName(fileName)) {
       if (!System.IO.Directory.Exists(filePath)) System.IO.Directory.CreateDirectory(filePath);
       file.SaveAs(filePath + fileName);

       // Save to DB
       string id = files.AllKeys[i].Substring(5);
       AttachmentInfo item = new AttachmentInfo();
       item.Description = HttpContext.Current.Request.Form["filedesc_" + id].Trim();
       item.Url = uploadPath + fileName;
       item.Grade = grade;
       item.GradeID = gradeid;

       new AttachmentBLL().CreateAttachment(item);
      }
     }
    }
   }
  }

  /// <summary>
  /// Check the file's extension is valid or not.
  /// </summary>
  private static bool CheckExtensionName(string fileName) {
   if (FileType == ".*") return true;

   if (FileType.IndexOf(System.IO.Path.GetExtension(fileName)) == -1)
    return false;
   else
    return true;
  }

  /// <summary>
  /// Generate a new filename from the old filename.
  /// </summary>
  private static string GenerateFileName(string fileName) {
   StringBuilder sb = new StringBuilder();
   sb.Append(new Random().Next(100, 999).ToString());
   sb.Append("_");
   sb.Append(DateTime.Now.ToString("HHmmss"));
   sb.Append("_");
   sb.Append(fileName);

   return sb.ToString();
  }
 }

用的时候只需要调用: save()方法就可以了




posted @ 2008-06-04 13:20  yeyang  阅读(11166)  评论(2)    收藏  举报