How to turn a byte [] into a file uploaded into a C # UploadFile

1

In the past I was able to get the file path through the component, but now after searching I found that it is no longer possible to get the file path on the client for security reasons, etc. In an old application I had a method with this code block below, however it 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 uploaded by a UploadFile to Byte [].

Explaining better:

I'm using this component:

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

InthefirstcodeIpostednoticethatthefirstparametertoFilestreamisthe"file path". My problem is that the FILEUPLOAD component does not give me the file path! And I'd like to know how I'll do this file conversion to byte [].

    
asked by anonymous 15.04.2015 / 13:39

3 answers

2

The way you were doing, taking the path of the file and then opening a Stream of this path would be problematic when publishing the application to a server, 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, it would not find the file.

The FileUpload component already contains the file itself, you do not need to "load it" again.

You can do as this answer from Tech Jerk .

After creating the method that it 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 your method in postback this 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;)

    
20.04.2015 / 20:11
0

I do not know if it was a hurried reading, but I did not exactly understand your question. Anyway, I'm sending below the way I work with uploading files. My systems are in MVC, however it is easy to 'convert' the code below.

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

Upload File

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 Definition

 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 entire upload process. In this case, all classes with the exception of JsonResult UploadArquivo() are within:

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

I do not know if the answer helped, if you edit your question with further instructions. I edit the answer.

    
15.04.2015 / 13:53
0

See if it helps:

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