0

i want to download varbinary stored in database as a file. I am able to download the file, however all the file that downloaded from my application are unable to open. I noticed that i upload pdf file with size 200 kb. But when i download that file, its only return 30 byte.

Here is the code:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(Upload model, HttpPostedFileBase uploadFile, String random_number, String rcf_number)
    {
        var db = new RCFOnlineEntities();
        if(uploadFile != null)
        {
            byte[] bytes;
            using (BinaryReader br = new BinaryReader(uploadFile.InputStream))
            {
                bytes = br.ReadBytes(uploadFile.ContentLength);
            }

            model.file_base6 = bytes;
            model.file_ext = uploadFile.ContentType;
            model.file_name = uploadFile.FileName;
            model.rcfnumber = rcf_number;
            model.randomnumber = random_number;
        }

      

        db.Uploads.Add(model);
        db.SaveChanges();

        return RedirectToAction("Edit", "GetRCFOnline", new { random_number = random_number });
    }

[HttpGet]
   public FileResult DownLoadFile(int id, String random_number)
   {

      List<Upload> ObjFiles = GetUploadClasses(random_number);

      var FileById = (from FC in ObjFiles
                       where FC.file_id.Equals(id)
                       select new { FC.file_name, FC.file_base6 , FC.file_ext}).ToList().FirstOrDefault();


    
      return File(FileById.file_base6, FileById.file_ext, FileById.file_name);

   }

Could you tell me where is the error within my code ?

1 Answer 1

1

Solution-1:

Use uploadFile.InputStream.Length instead uploadFile.ContentLength for correct upload file size i.e.

using (BinaryReader br = new BinaryReader(uploadFile.InputStream))
{
     bytes = br.ReadBytes(uploadFile.InputStream.Length);
}

Solution-2:

If BinaryReader is not a fixed requirement then use below solution to get uploaded file's bytes i.e.

byte[] bytes = new byte[uploadFile.InputStream.Length];
uploadFile.InputStream.Read(bytes, 0, bytes.Length);
Sign up to request clarification or add additional context in comments.

2 Comments

its says "cannot convert from long to int"
if you need your stream in bytes and BinaryReader is not a fixed requirement then you can simply use solution-2 I have updated in my above answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.