前端通过FormData上传文件到服务器端

前端代码

html

<input type="file" accept=".zip" onchange="uploadFile(this.value);">

JavaScript

function uploadFile(file) {
    if (!file) {
        return;
    }

    // upload params
    var data = {
        UserID: top.BDCGlobal.USERINFO.user_id,
        ProjectID: inProjInfo.ID,
        flag: "jnkcydoc_importZIP"
    };

    var formData = new FormData();
    formData.append("Files", $("#btn_importZIP input[type=file]").prop("files")[0]);
    for (var d in data) {
        formData.append(d, data[d]);
    }

    // upload
    $.ajax({
        url: UploadFileService.url,
        type: "post",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (res) {
            if (res.success) {
                console.log("import ZIP success");
            }
        },
        error: function (eres) {
            console.log("import ZIP err");
        }
    });

}

后端c#解析代码

public void importZIP(HttpContext context)
{
      HttpFileCollection files = context.Request.Files;

      string UserID = context.Request.Form["UserID"];
      string ProjectID = context.Request.Form["ProjectID"];

      if (files.Count < 1)
      {
          context.Response.Write("{\"success\":0,\"message\":\"未找到文件!\"}");
          HttpContext.Current.ApplicationInstance.CompleteRequest();
          return;
      }

      // 单文件,取出最后一个
      HttpPostedFile file = files[files.Count - 1];


      // check file ext
      string extStr = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
      
      if (extStr != ".zip")
      {
          context.Response.Write("{\"success\":0,\"message\":\"不是标准的ZIP文件!\"}");
          HttpContext.Current.ApplicationInstance.CompleteRequest();
          return;
      }

      string basePath = AppDomain.CurrentDomain.BaseDirectory;//文件基目录
      string relativePath = "Files\\zip\\" + UserID + "\\";//服务器上的相对路径
      string path = basePath + relativePath;
      if (Directory.Exists(path))
          Directory.Delete(path, true);
      Directory.CreateDirectory(path);

      string fileName = file.FileName;
      file.SaveAs(path + fileName);
       
      string result = "{\"success\": 1, \"result\": 1}"; 
      context.Response.Write(result);
      HttpContext.Current.ApplicationInstance.CompleteRequest();
      return; 
  }


你可能感兴趣的:(C#,JavaScript,前端,javascript,c#)