如何获取POST请求内容并使用c#.NET保存?

时间:2013-02-24 08:02:05

标签: c# asp.net .net vb.net http

我有android应用程序向Http POST页面发出asp.net请求。

我想实现接收此请求的asp.net页面并将其内容保存到文件中(它的文件上传)。

非常感谢给我样品

2 个答案:

答案 0 :(得分:1)

我是如何在asp.net应用程序中执行此操作,该应用程序从Android接收图像, 关于我收到它的简单参数

context.Request["Yourparameter"]


public class RecieveMail : IHttpHandler
{
    private string _emailAdressTo;
    private string _imageUrl;
    private EmailFactory _emailFactory;

    public void ProcessRequest(HttpContext context)
    {
        ImageFactory factory = new ImageFactory(context);
        try
        {
            _imageUrl = factory.SaveImage("uploaded");

            if (string.IsNullOrEmpty(context.Request["from"]) || string.IsNullOrEmpty(context.Request["to"])) return;

            _emailFactory = new EmailFactory(_imageUrl);
            if (_emailFactory.SendMail(context.Request["from"], context.Request["to"]))
                context.Response.Write(!factory.DeleteImage(_imageUrl) ? "Email sent" : "Image deleted");
        }
        catch (Exception ex)
        {
            context.Response.Write(" error converting " + ex.Message);
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }    
}

//这是图像保存工厂

public class ImageFactory
{
    private readonly HttpContext _context;
    private Image _image;

    public ImageFactory(HttpContext context)
    {
        _context = context;
    }

    /// <summary>
    /// Get image by name from post
    /// </summary>
    /// <param name="ctxImageParamName">image that have been posted in email</param>
    /// <returns></returns>
    public string SaveImage(string ctxImageParamName)
    {
        if (string.IsNullOrEmpty(_context.Request[ctxImageParamName])) return null;
        string url = GenerateImagePath("FrameMe");
        ByteArrayToImageAndSave(Decode(_context.Request[ctxImageParamName]), url);
        return url;
    }

    public bool DeleteImage(string url)
    {
        try
        {
            if (!File.Exists(url)) return false;
            File.Delete(url);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }    
    }

    private string GenerateImagePath(string directory)
    {
        return _context.Server.MapPath(string.Format("~/Images/{1}/Image1_{0}.jpg", DateTime.Now.ToString("ddMMyyyyHHmmss"), directory));
    }

    private void ByteArrayToImageAndSave(byte[] byteArrayIn, string imageUrl)
    {
        try
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            _image = Image.FromStream(ms);
            _image.Save(imageUrl, new ImageFormat(Guid.NewGuid()));
            _image.Dispose();
        }
        catch (Exception ex)
        {
            _image = null;
        }
    }

    private byte[] Decode(string str)
    {
        return Convert.FromBase64String(str);
    }
}

答案 1 :(得分:0)

使用asp.net中的Request对象检索页面的发布信息。

e.g:

Request.Form["NameOfVar"]