How to implement a file download in ASP.NET AJAX

前端 未结 4 1363
-上瘾入骨i
-上瘾入骨i 2021-02-04 15:22

I would like to use standard ASP.NET file download response, like in other Stack Overflow question.

Response.ContentType = \"application/octet-stream\";
Respo         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 16:03

    You can try making a handler for this work.It is more secure if you can modify well. For this work,you need to encrypt file path in your page where you put a link for the file.

    Your link to file 
    //{0} -> Encrypted file path
    //target = _blank force browser to download file in another window
    

    There are lots of encryption techniques in here

    In your Handler page, you need to decrypt the file path into original one so you can read it with System.IO libraries.

    context.Response.ContentType = ""; //-->MimeType for your file's extension
    

    You can specify your MimeType by Registry unless your mime-type is static as images.

    string mimeType = Registry.GetValue(string.Format(@"HKEY_CLASSES_ROOT\.{0}",
                      Path.GetExtension(decryptedfilePath)), "Content Type", null).ToString();
    
    //Then everything is ready for download
    
    byte[] buffer = File.ReadAllBytes(decryptedfilePath);
    context.Response.OutputStream.Write(buffer, 0 , buffer.Length);
    context.Response.Flush();
    

    Good Luck.

提交回复
热议问题