سؤال

I have some EML Files with attachments. I've parsed the EML files pulled out the attachments, and if I do this :

File.WriteAllBytes(attachment.Name, Convert.FromBase64String(attachment.Data))

I get the attachment dumped to a file. What I want to do is have a link so that when the user clicks on it, the attachment downloads.

Easy enough if its a file already on disk, but instead I have this base64encoded string that I can convert to a byte array. How can I take this base64encoded string (or the converted byte array) and generate a link directly to that?

Thanks

هل كانت مفيدة؟

المحلول

You would return back a FileResult class with the data from some other action method:

 public ActionResult DownloadData(string fileNameOrWhatever)
 {
      byte[] fileData = ...;

      return File(fileData, "someMimeType", "downloadNameToBeDisplayed");
 }

Your link would then point here:

<a href="/DownloadData/Something">Click me!</a>

نصائح أخرى

Is this MVC? You can create a controller method that returns a FileStreamResult, create an action to link to it and write the data in.

I have a project where I create an Excel document on the server and the user will receive the file as a download when they navigate to the specific action. Here's the code I'm using, and I think you can refactor it for what you need:

    public void GetExcel(string id)
    {
        ExcelPackage p = new ExcelPackage(); 

        //code to add data to the document            

        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=BitlyReport.xlsx");
        MemoryStream stream = new MemoryStream(p.GetAsByteArray());
        Response.OutputStream.Write(stream.ToArray(), 0, stream.ToArray().Length);

        Response.Flush();

        Response.Close();
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top