Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileUpload to FileStream

I am in process of sending the file along with HttpWebRequest. My file will be from FileUpload UI. Here I need to convert the File Upload to filestream to send the stream along with HttpWebRequest. How do I convert the FileUpload to a filestream?

like image 734
Gopi Avatar asked Jun 18 '10 08:06

Gopi


People also ask

What is the use of FileStream?

Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output.

What is FileUpload?

Uploading is the transmission of a file from one computer system to another, usually larger computer system. From a network user's point-of-view, to upload a file is to send it to another computer that is set up to receive it.

How do I view a FileStream file?

using FileStream fs = File. OpenRead(fileName); With File. OpenRead we open a file for reading.

Which control is used to display a textbox and a browse button that enable you to browse a file from the local or remote machine to upload it on a Web server *?

The FileUpload control allows the user to browse for and select the file to be uploaded, providing a browse button and a text box for entering the filename.


2 Answers

Since FileUpload.PostedFile.InputStream gives me Stream, I used the following code to convert it to byte array

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[input.Length];
    //byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}
like image 161
Gopi Avatar answered Sep 22 '22 09:09

Gopi


Might be better to pipe the input stream directly to the output stream:

inputStream.CopyTo(outputStream);

This way, you are not caching the entire file in memory before re-transmission. For example, here is how you would write it to a FileStream:

FileUpload fu;  // Get the FileUpload object.
using (FileStream fs = File.OpenWrite("file.dat"))
{
    fu.PostedFile.InputStream.CopyTo(fs);
    fs.Flush();
}

If you wanted to write it directly to another web request, you could do the following:

FileUpload fu; // Get the FileUpload object for the current connection here.
HttpWebRequest hr;  // Set up your outgoing connection here.
using (Stream s = hr.GetRequestStream())
{
    fu.PostedFile.InputStream.CopyTo(s);
    s.Flush();
}

That will be more efficient, as you will be directly streaming the input file to the destination host, without first caching in memory or on disk.

like image 32
Extremeswank Avatar answered Sep 22 '22 09:09

Extremeswank