How to byte[] a uploaded file into a C#Uploadfile

Asked

Viewed 2,414 times

1

In the past I was able to pick up the file path through the component, but now after researching I discovered that it is no longer possible to pick up the file path in the client for security reasons etc. In an old application I had a method with this code block below, but is not currently functional with Uploadfile.

using (var stream = new FileStream(caminhoArquivo, FileMode.Open, FileAccess.Read))
{
    using (var reader = new BinaryReader(stream))
    {
        arquivo = reader.ReadBytes((int)stream.Length);
    }
}

The question is: How to do this procedure of transforming a file loaded by an Uploadfile to Byte[].


Explaining better:

I’m using this component:

<asp:FileUpload ID="FileUpload1" runat="server" />

inserir a descrição da imagem aqui

In the first code I posted, note that the first parameter for Filestream is the "path". My problem is that the FILEUPLOAD component does not give me the file path! And I would like to know how to do this file to byte conversion[].

  • I don’t understand what you want. You are reading the binary file correctly. I imagine you are talking about the WebClient.UploadFile, it is used to send a file, not to receive.

  • This method is correct, but the path File we could not catch by Uploadfile more... If I run this method by taking (Uploadfile.PostedFile.Filename) from Notfound. Now you understand?

  • But what is the doubt?

  • The method that Uploadfile has to get information about the file is this (Uploadfile.PostedFile.Filename), but it only brings the name + file extension. Ai da notfound... that’s my problem.

  • Show me how you’re using it.

  • @bigown I updated the topic explaining better.

Show 1 more comment

3 answers

2

The way you were doing, taking the path of the file and then opening a stream of this path would give problem when publishing the application on a server, on your local machine would work since the server and client would be on the same machine and the file is on the same machine, but on a server on a separate machine, would not find the file.

The Fileupload component already contains the file itself, no need to "load=it" again.

You can do how that Tech Jerk response.

After creating the method he puts in the answer:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[input.Length];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

You call in your method in the postback that way:

byte[] arquivo = ReadFully(FileUpload1.PostedFile.InputStream);

Remember to check before you even own the file, if the stream is not null and other validations ;)

0

I don’t know if it was a hasty read, but I didn’t quite understand your question. Anyway, I’m sending down the way I work with uploading files. My systems are in MVC, but it is easy to 'convert' the code below.

Class that receives file

[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
    public JsonResult UploadArquivo()
    {
        HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;
        if (file != null && file.ContentLength > 0)
        {
            var ftp = new Helpers.Ftp();
            string nome = ftp.GerarNome(file.FileName.Substring(file.FileName.LastIndexOf(".")));
            if (ftp.UploadArquivo(file, nome, "Web/arquivos/"))
                return Json(new { Nome = nome }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { Nome = "" }, JsonRequestBehavior.AllowGet);
        }
        return Json(new { Nome = "" }, JsonRequestBehavior.AllowGet);
    }

Definition of the Uploadfile

public Boolean UploadArquivo(HttpPostedFileBase file, string nome, string diretorio)
    {

        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp+diretorio + nome);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            request.Credentials = new NetworkCredential(usuario, senha);
            request.UsePassive = false;

            request.Proxy = null;

            byte[] fileContents = new byte[file.ContentLength];
            file.InputStream.Position = 0;
            file.InputStream.Read(fileContents, 0, file.ContentLength);
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            response.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }

Ftp setting

 private string ftp;
    private string usuario;
    private string senha;

    public Ftp()
    {
        ftp = "";
        usuario = "";
        senha = "";
    }

File name generator

 public string GerarNome(string extensao)
        {
            return DateTime.Now.ToString().Replace(":", "").Replace("/", "").Replace(" ", "") + extensao;
        }

With this code you can handle the whole upload process. In this case, all classes except JsonResult UploadArquivo() are inside:

namespace Ui.Web.Helpers
{
    public class Ftp{
// Código
}
}

I don’t know if the answer helped, if you edit your question with further instructions. I edit the answer.

0

See if it helps:

byte[] byteArray = null;
using(var ms = new System.IO.MemoryStream())
{
   f.PostedFile.InputStream.CopyTo(ms);
   byteArray = ms.ToArray();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.