如何在asp.net 4.0中发布带有web请求的文件

本文关键字:布带 web 请求 文件 asp net | 更新日期: 2023-09-27 17:58:29

我只想用服务器文件夹中的多个文件发布web请求。我在这里读了这篇文章。我只想在微软使用这种技术。网来自NuGet的Http包。这是我的代码:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Net.Http;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create web request object
        WebRequest objWebRequest;
        // Set url properties
        string url = "http://localhost:16047/EasyWeb/Admin/Post_History.aspx";
        objWebRequest = WebRequest.Create(url);
        objWebRequest.Method = "POST";
        // add sample form data
        ArrayList queryList = new ArrayList();
        queryList.Add(string.Format("{0}={1}", "title", HttpUtility.UrlDecode("From Admin to All Users 1")));
        queryList.Add(string.Format("{0}={1}", "desc", HttpUtility.UrlEncode("hi all users 1")));
        queryList.Add(string.Format("{0}={1}", "category", HttpUtility.UrlEncode("Test")));
        queryList.Add(string.Format("{0}={1}", "touser", HttpUtility.UrlEncode(string.Empty)));
        queryList.Add(string.Format("{0}={1}", "status", HttpUtility.UrlEncode(string.Empty)));
        queryList.Add(string.Format("{0}={1}", "group", HttpUtility.UrlEncode(string.Empty)));
        queryList.Add(string.Format("{0}={1}", "isfile", HttpUtility.UrlEncode("True")));
        queryList.Add(string.Format("{0}={1}", "sentdatetime", HttpUtility.UrlEncode(DateTime.Now.ToString())));
        var dir = new DirectoryInfo(Path.Combine(HttpRuntime.AppDomainAppPath, "Files/"));
        int cnt = 0;
        foreach (FileInfo file in dir.GetFiles())
        {
            if (file.Exists)
            {
                cnt++;
               Upload(url, "file " + cnt.ToString(), file.Open(FileMode.Open), System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/PostedFile/" + file.Name)));
            }
        }
        // Set the encoding type
        objWebRequest.ContentType = "application/x-www-form-urlencoded";
        string Parameters = String.Join("&", (String[])queryList.ToArray(typeof(string)));
        objWebRequest.ContentLength = Parameters.Length;
        //we get back the response after submission
        HttpWebResponse objHttpWebResponse;
        objHttpWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
    }
    private System.IO.Stream Upload(string url, string param1, Stream fileStream, byte[] fileBytes)
    {
        HttpContent stringContent = new StringContent(param1);
        HttpContent fileStreamContent = new StreamContent(fileStream);
        HttpContent bytesContent = new ByteArrayContent(fileBytes);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent, "file1", "file1");
            formData.Add(bytesContent, "file2", "file2");
            var response = client.PostAsync(url, formData).Result;
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            return response.Content.ReadAsStreamAsync().Result;
        }
    }
}

这是我的接收器网络应用程序代码:

 protected void Page_Load(object sender, EventArgs e)
    {
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                Session["Username"] = db.Users.Where(u => u.type_id.Equals("1")).Select(u => u.Username).FirstOrDefault();
                string title = null, desc = null, category = null, touser = null, status = null, group = null, isfile = null, sentdatetime = null;
                foreach (string strName in Request.Params)
                {
                    string strValue = Request.Form[strName];
                    switch (strName)
                    {
                        case "title":
                            title = strValue;
                            break;
                        case "desc":
                            desc = strValue;
                            break;
                        case "category":
                            category = strValue;
                            break;
                        case "touser":
                            touser = strValue;
                            break;
                        case "status":
                            status = strValue;
                            break;
                        case "group":
                            group = strValue;
                            break;
                        case "isfile":
                            isfile = strValue;
                            break;
                        case "sentdatetime":
                            sentdatetime = strValue;
                            break;
                    }
                }
                if(string.IsNullOrEmpty(title) || string.IsNullOrEmpty(desc) || string.IsNullOrEmpty(category) || string.IsNullOrEmpty(isfile))
                {
                    if (!Page.IsPostBack)
                    {
                        var query = Helper.GetProfile().ToList();
                        foreach (var item in query)
                        {
                            GV_ViewPost.PageSize = item.Page_Size;
                        }
                        Panel_AddNew.Visible = false;
                        Panel_View.Visible = false;
                        Session["CommandName"] = "Inbox";
                        Session["ColumnName"] = null;
                        Session["SearchtText"] = null;
                        this.FillGrid(Session["CommandName"].ToString(), (String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
                        Bind_DDL_Column_List();
                        Bind_DDL_Category_List();
                        //Bind_Users_List();
                        Bind_DDL_Group();
                        Bind_DDL_Status();
                    }
                    this.GetData();
                }
                else
                {
                    int category_id = db.Categories.Where(c => c.Category_name.Equals(category)).Select(c => c.Id).FirstOrDefault();
                    int user_id = db.Users.Where(u => u.type_id.Equals("1")).Select(u => u.Id).FirstOrDefault();
                    System.Nullable<int> touser_id = null;
                    System.Nullable<int> status_id = null;
                    System.Nullable<int> group_id = null;
                    System.Nullable<DateTime> sent_datetime = null;
                    if (!string.IsNullOrEmpty(touser))
                    {
                        touser_id = db.Users.Where(u => (u.First_name + ' ' + u.Last_name).Equals(touser)).Select(u => u.Id).FirstOrDefault();
                    }
                    if (!string.IsNullOrEmpty(status))
                    {
                        status_id = db.Status.Where(s => s.status_name.Equals(status)).Select(s => s.Id).FirstOrDefault();
                    }
                    if (!string.IsNullOrEmpty(group))
                    {
                        group_id = db.Groups.Where(g => g.Group_name.Equals(group)).Select(g => g.Id).FirstOrDefault();
                    }
                    bool is_file = Convert.ToBoolean(isfile);
                    if (!string.IsNullOrEmpty(sentdatetime))
                    {
                        sent_datetime = DateTime.Parse(sentdatetime);
                    }
                    Post myPost = new Post();
                    myPost.Title = title;
                    myPost.Category_id = category_id;
                    myPost.Description = desc;
                    myPost.User_id = user_id;
                    myPost.ToUser_id = touser_id;
                    myPost.status_id = status_id;
                    myPost.group_id = group_id;
                    myPost.IsFileAttached = is_file;
                    myPost.Sent_Datetime = sent_datetime;
                    db.Posts.InsertOnSubmit(myPost);
                    db.SubmitChanges();
                    int newId = myPost.Id;
                    if (is_file.Equals(true))
                    {
                        string val ;
                        double tot_file_size = 0;
                        for (int i = 0; i < Request.Params.AllKeys.AsQueryable(k=>k.); i++)
                        {
                            File myFile = new File();
                            HttpPostedFile uploadfile = fileCollection[i];
                            string fileTitle = Path.GetFileName(uploadfile.FileName);
                            string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                            string fileType = System.IO.Path.GetExtension(fileTitle).ToString().ToLower();
                            myFile.Post_History_id = newId;
                            myFile.File_Title = fileTitle;
                            myFile.File_name = fileName;
                            myFile.File_ext = fileType;
                            double file_size = int.Parse(uploadfile.ContentLength.ToString()) / 1024;
                            tot_file_size += file_size;
                            myFile.File_Size = file_size;
                            if (uploadfile.ContentLength > 0)
                            {
                                uploadfile.SaveAs(Server.MapPath("~/PostFiles/") + fileName + fileType);
                                db.Files.InsertOnSubmit(myFile);
                                db.SubmitChanges();
                            }
                        }
                        db.UpdatePostField(newId, "TotalFileSize", tot_file_size.ToString());
                    }
                }
            }
            ImageButton7.Attributes.Add("onmouseover", "src='../images/export_over.gif'");
            ImageButton7.Attributes.Add("onmouseout", "src='../images/export.gif'");
            ImageButton8.Attributes.Add("onmouseover", "src='../images/print_over.gif'");
            ImageButton8.Attributes.Add("onmouseout", "src='../images/print.gif'");
            ImageButton9.Attributes.Add("onmouseover", "src='../images/grouptree_over.gif'");
            ImageButton9.Attributes.Add("onmouseout", "src='../images/grouptreed.gif'");
            btnFirst.Attributes.Add("onmouseover", "src='../images/first_over.gif'");
            btnFirst.Attributes.Add("onmouseout", "src='../images/First.gif'");
            btnPrev.Attributes.Add("onmouseover", "src='../images/prev_over.gif'");
            btnPrev.Attributes.Add("onmouseout", "src='../images/Prev.gif'");
            btnNext.Attributes.Add("onmouseover", "src='../images/next_over.gif'");
            btnNext.Attributes.Add("onmouseout", "src='../images/next.gif'");
            btnLast.Attributes.Add("onmouseover", "src='../images/last_over.gif'");
            btnLast.Attributes.Add("onmouseout", "src='../images/last.gif'");
            ImageButton14.Attributes.Add("onmouseover", "src='../images/gotopage_over.gif'");
            ImageButton14.Attributes.Add("onmouseout", "src='../images/gotopage.gif'");
            ImageButton16.Attributes.Add("onmouseover", "src='../images/search_over.gif'");
            ImageButton16.Attributes.Add("onmouseout", "src='../images/Search.gif'");
    }

通过尝试运行此代码,我发现错误如下:

You must provide a request body if you set ContentLength>0 or SendChunked==true.  Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.Net.ProtocolViolationException: You must provide a request body if you set ContentLength>0 or SendChunked==true.  Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.
Source Error: 

Line 55:         //we get back the response after submission
Line 56:         HttpWebResponse objHttpWebResponse;
Line 57:         objHttpWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
Line 58:     }
Line 59:     private System.IO.Stream Upload(string url, string param1, Stream fileStream, byte[] fileBytes)
Source File: c:'Documents and Settings'Administrator'My Documents'Visual Studio 2008'WebSites'WebRequest'Default.aspx.cs    Line: 57 
Stack Trace: 

[ProtocolViolationException: You must provide a request body if you set ContentLength>0 or SendChunked==true.  Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.]
   System.Net.HttpWebRequest.GetResponse() +6038249
   _Default.Page_Load(Object sender, EventArgs e) in c:'Documents and Settings'Administrator'My Documents'Visual Studio 2008'WebSites'WebRequest'Default.aspx.cs:57
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

如何在asp.net 4.0中发布带有web请求的文件

问题在于您试图获取所有文件:

foreach (FileInfo file in Path.Combine(HttpRuntime.AppDomainAppPath, "Files/"))

你应该使用这样的东西:

foreach (string filename in Directory.GetFiles(Path.Combine(HttpRuntime.AppDomainAppPath, "Files/")))
{
    FileInfo file = new FileInfo(filename);
    ...
}
var dir= new DirectoryInfo(Path.Combine(HttpRuntime.AppDomainAppPath, "Files/"));
foreach (FileInfo file in dir.GetFiles())
{
    if (file.Exists)
    {
         // upload 
    }
}