在C#中处理HttpPostedFile [英] Handling HttpPostedFile in C#

查看:195
本文介绍了在C#中处理HttpPostedFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#.net Web应用程序,可以通过POST方法将文件发送到另一个应用程序.在第二个应用程序中,我具有以下代码来检索发布的文件.

I have a C#.net web application that can send (by POST method) files to another application. In the second application I have the below code to retrieve the posted file.

HttpPostedFile hpf = Request.Files[0];

现在我可以通过代码保存文件了

Now I can save the file by the code

hpf.SaveAs("The path to be saved");

但是我需要再次将其发送到另一个应用程序而不将其保存在这里(不保存在第二个appln中,我需要将其发送到第三个appln).

But I need to send it again to another application without saving it here (without saving in 2nd appln I need to send it to a third appln).

(现在我可以做的是,通过提供与我在第一个应用程序中完全相同的路径,将文件保存在第二个应用程序中,然后将其发布到第三个应用程序.但是我需要另一个解决方案.)

(Now I can do is that save the file in second application and from there post it to the third application by giving the path exactly same as what I did in my 1st application. But I need another solution.)

我尝试了hpf.fileName,但是它只给出了文件名(例如:test.txt).当我尝试如下

I tried hpf.fileName but its giving only the filename (eg:test.txt). When I tried like below

string file = hpf.FileName;
string url = "the url to send file";
    using (var client = new WebClient())
    {
        byte[] result = client.UploadFile(url, file);
        string responseAsString = Encoding.Default.GetString(result);
    }

发生了类似"WebClient请求期间发生异常"之类的WebException.

A WebException occured like 'An exception occurred during a WebClient request.'

在C#.net中有什么方法可以做到吗?

Is there any method to do it in C# .net?

推荐答案

用于创建字节数组 如何从HttpPostedFile创建字节数组

这是一种在Web服务中保存字节的方法

Here is a method to save bytes in webservice

[WebMethod]
public string UploadFile(byte[] f, string fileName, string bcode)
{
    if (bcode.Length > 0)
    {
        try
        {
            string[] fullname = fileName.Split('.');
            string ext = fullname[1];
            if (ext.ToLower() == "jpg")
            {
                MemoryStream ms = new MemoryStream(f);
                FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath("~/bookimages/zip/") + bcode+"."+ext, FileMode.Create);
                ms.WriteTo(fs);
                ms.Close();
                fs.Close();
                fs.Dispose();


            }
            else
            {
                return "Invalid File Extention.";
            }
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }
    else
    {
        return "Invalid Bookcode";
    }

    return "Success";
}

这篇关于在C#中处理HttpPostedFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆