文件上传到服务器中的文件夹

时间:2013-04-13 12:58:14

标签: jquery asp.net json

我只想将上传的文件保存到服务器中的文件夹中。我的系统设计有UI和服务器部分.UI是完全HTML,服务器端是ASP.net。数据传输是通过json代码。

假设我在UI中有HTML文件控件,那么我该如何将其上传到服务器。

任何人都可以用一个例子告诉我

代码示例

 $("#btn_AddDoc").click( function (e) {
          e.preventDefault();
          var InsDocDet = {};
          InsDocDet.docname=$("#DocName").val();

          InsDocDet.ownerUser=1;
          InsDocDet.catid=$("#drp_cat").val();
          InsDocDet.createDatetime=new Date();
          InsDocDet.description_d=$("#Desc").val();
          InsDocDet.comments_=$("#cmnts").val();
          InsDocDet.deptid_=1;
          InsDocDet.con_type=1;
          InsDocDet.size_=1;
          InsDocDet.Doc_status="up";
          var fullPath =$("#doc_upload").val(); //document.getElementById('doc_upload').value;
          if (fullPath) {
          var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
          var filename = fullPath.substring(startIndex);
          if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
          filename = filename.substring(1);
          InsDocDet.file_name=filename;
          $.ajax({
              type: "POST",
            // <!-- url: "http://localhost/EMRDMSService/Service.asmx/User_Login",-->
             url: "http://localhost/EMRDMSService/Service.asmx/srv_Insert_Document",
              data: "{ins_Doc:" + JSON.stringify(InsDocDet) + "}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (r) {                     
                              console.log(r.d.STAT);
              }
          });
      });

在网络服务中

public string srv_Insert_Document(insert_doc_details ins_Doc)
{
    InsDoc_Ret doc_ret = new InsDoc_Ret();
    try
    {

        string filename = Path.GetFileName(ins_Doc.file_name);
        string path = Server.MapPath("~/");
        File_Doc.SaveAs(Server.MapPath(Path.Combine("~/Files/" + dept_name + "/", filename)));
        string ctype = File_Doc.PostedFile.ContentType;
        int len = File_Doc.PostedFile.ContentLength;
        double size = len / 1024;
        string sizkb = Convert.ToString(size) + " KB";
        string fname = dept_name + "/" + filename;






        int doc_id = newdb_class.Insert_Data_Scaler("INSERT INTO dms_document_details (DOC_NAME,FILE_NAME,OWNER_USER,CAT_ID,CREATE_DATE,DESCRIPTION,COMMENTS,DEPT_ID,contype,Size,DocStatus) VALUES ('" + ins_Doc.docname + "','" + ins_Doc.file_name + "','" + ins_Doc.ownerUser + "','" + ins_Doc.catid + "',NOW(),'" + ins_Doc.description_d + "','" + ins_Doc.comments_ + "','" + ins_Doc.deptid_ + "','" + ins_Doc.con_type + "','" + ins_Doc.size_ + "','" + ins_Doc.Doc_status + "')");
        doc_ret.SID = "1";
        doc_ret.STAT="SUCCESS";

    }
    catch (Exception ex)
    {
        doc_ret.SID = "1";
        doc_ret.STAT = "FAIL";
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    string strJSON = js.Serialize(doc_ret);
    return strJSON;

}

这里的代码中服务中的“File_Doc”是指asp.net中的文件上传控件。那么怎么能用html文件控制来替换它。


我得到了一些代码

 public string srv_Insert_Document(insert_doc_details ins_Doc)
{
    InsDoc_Ret doc_ret = new InsDoc_Ret();
    try
    {
        DataTable dt = new DataTable();
        dt = newdb_class.Read_Data("SELECT Dept_Name FROM dms_dept_details WHERE Dept_id='" + ins_Doc.deptid_ + "'");
        string dept_name = dt.Rows[0][0].ToString().Trim();
        string filename = Path.GetFileName(ins_Doc.file_name);
        string path = Server.MapPath("~/");
        HttpPostedFile file = Request.Files["myFile"];
        if (file != null && file.ContentLength > 0)
        {
            string fname = Path.GetFileName(file.FileName);
            file.SaveAs(Server.MapPath(Path.Combine("~/Files/" + dept_name + "/", filename)));
        }

        string ctype = file.ContentType;
        int len = file.ContentLength;
        double size = len / 1024;
        string sizkb = Convert.ToString(size) + " KB";


        string fname_ins = dept_name + "/" + filename;






        int doc_id = newdb_class.Insert_Data_Scaler("INSERT INTO dms_document_details (DOC_NAME,FILE_NAME,OWNER_USER,CAT_ID,CREATE_DATE,DESCRIPTION,COMMENTS,DEPT_ID,contype,Size,DocStatus) VALUES ('" + ins_Doc.docname + "','" + ins_Doc.file_name + "','" + ins_Doc.ownerUser + "','" + ins_Doc.catid + "',NOW(),'" + ins_Doc.description_d + "','" + ins_Doc.comments_ + "','" + ins_Doc.deptid_ + "','" + ins_Doc.con_type + "','" + ins_Doc.size_ + "','" + ins_Doc.Doc_status + "')");
        doc_ret.SID = "1";
        doc_ret.STAT="SUCCESS";

    }
    catch (Exception ex)
    {
        doc_ret.SID = "1";
        doc_ret.STAT = "FAIL";
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    string strJSON = js.Serialize(doc_ret);
    return strJSON;

}

但我在HttpPostedFile file = Request.Files["myFile"];

中收到错误

即当前上下文中不存在请求

1 个答案:

答案 0 :(得分:1)

没有。上传文件需要完整的回发。

您可以模拟将ajax调用发布到隐藏的iFrame(因此您的页面不会更改)。然后使用jquery / javascript检查iFrame的内容,您可以看到上传是否成功并刷新屏幕的某些部分。

如果您使用的是ASP.NET MVC3或MVC4,请举例如下:http://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3.aspx

如果你想在JS中使用更通用的方法:http://tips.itliveweb.com/ajax/upload-image-using-iframe-javascript-ajax.html