【问题标题】:How to generate a POST request with file upload and other fields from asp.net app?如何从 asp.net 应用程序生成带有文件上传和其他字段的 POST 请求?
【发布时间】:2014-08-21 12:43:31
【问题描述】:

谁能给我一个简短的例子,说明如何从 ASP.NET 应用程序在单个 POST 请求中上传文件并发送多个文本字段?

例如,从我在内部服务器上运行的 asp.net 应用程序中,我想使用 POST 请求将文件连同 2 个文本字段(例如名称、日期)上传到另一台服务器。我认为我需要使用 WebClient,但我不太确定如何在一个请求中将多个字段与文件上传结合起来。

谢谢。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    一个好的 AJAX 选项是发送一个 FormData 对象(注意:与 IE

    //初始化表单数据的新实例 var uploadData = new FormData();

    //Get parameters 
    uploadData.append("ID", eID);
    uploadData.append("adPhoto", theImage);
    uploadData.append("field2", field2);
    
    //Make AJAX call 
    var xhr = new XMLHttpRequest();
    xhr.open("POST", Defaults.PhotoUploadService);
    xhr.send(uploadData);
    

    在后端...

    public static void UploadFile() {
    
    int ID = Context.Request.Params["ID"];
    string field = Convert.ToInt32(Context.Request.Params["field"]);
    
    //Get your photo here
    byte[] fileData = null;
    HttpPostedFile postedFile = Context.Request.Files["adPhoto"];
    
    using (var binaryReader = new BinaryReader(postedFile.InputStream))
          {
          fileData = binaryReader.ReadBytes(Context.Request.Files[0].ContentLength);
          }
    
    // Do whatever you have to do at this point...
    
    }
    

    有意义吗?希望对您有所帮助,这是一个好的开始!

    【讨论】:

    • 感谢您的回复。然而,这并不是我所追求的。我想在服务器端从我的 ASP.NET 应用程序执行您的 Ajax 示例。我怀疑我需要以与您使用 Ajax XMLHttpRequest 类似的方式使用 HttpRequest。也就是说,如果我只能将您的 Ajax 示例转换为 C#/ASP.NET 服务器代码,我就可以了。
    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2020-06-23
    • 2010-12-05
    • 2017-07-18
    相关资源
    最近更新 更多