0

I have checked many questions on StackOverflow, and also searched on many different websites for possible solutions, but I don't seem to find any answer. Some don't work, others are very old and don't work either.

I have saved .pdf files in SQL Server as binary. Seems to work. But I don't know how to retrieve the data and turn the byte[] back to the .pdf file and make it available for download.

This is my model, where I save the .pdf file in byte[]:

public class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Certificate { get; set; }
}

This is how I upload into database:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(string name, IFormFile certificate)
{
    Language language = new Language()
    {
        Name = name
    };

    if(certificate.Length > 0)
    {
        using (var stream = new MemoryStream())
        {
            await certificate.CopyToAsync(stream);
            language.Certificate = stream.ToArray();
        }
    }

    _context.Add(language);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

I would like it to be able to retrieve the data and then download it.

I appreciate any help.

4
  • What class are you using for the pdf file when you converted to bytes. Commented Mar 29, 2019 at 12:07
  • I am using IFormFile Commented Mar 29, 2019 at 12:48
  • Do you mean FromFile? FromFile crates a string which wil corrupt pdf which is binary. Better to use byte[] pdf = File.ReadAllBytes("filename"); File.WriteAllBytes("filename", pdf); Commented Mar 29, 2019 at 12:54
  • I will try this in another project. Thanks! Commented Mar 29, 2019 at 12:57

1 Answer 1

2

You need an action to return the bytes:

public async Task<IActionResult> GetCertificate(int id)
{
    var language = await _context.Languages.FindAsync(id);
    if (language == null)
        return NotFound();

    return File(language.Certificate, "application/pdf");
}

Then, you can simply link to this action.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you elaborate on "simply link to this action"? I have the same issue described by @Max. PDF files are stored in SQL Server but how to render them in an HTML element becomes the question. Are you suggesting use of an <embed> tag with a "src" attribute set to "controller/action"? Or, is there a better method?

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.