Handling HttpPostedFile in C#

血红的双手。 提交于 2019-12-08 03:18:55

问题


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");

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.)

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);
    }

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

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


回答1:


Thing is, if you don't want to use web service as suggested in the previous answer, you need to use InputStream property of your HttpPostedFile. You should use HttpWebRequest object to create request with your file content. There are lots of posts and tutorials around including this and this.




回答2:


for creating byte array How to create byte array from HttpPostedFile

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";
}


来源:https://stackoverflow.com/questions/15786656/handling-httppostedfile-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!