Download file from webservice - in ASP.NET site

后端 未结 4 2356
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 14:00

I want to push a file to the browser from a website using a webservice. I\'m currently reading the file into a base64 byte array, and returning that from the webservice. This w

4条回答
  •  梦谈多话
    2021-02-20 14:18

    First, rather than send a base64 byte array, have your web service simply return a byte array for your file. Response.OutputStream.Write() will automatically base64 encode your bytes, so you might as well have them un-encoded in your memory stream.

    Second, you'll need more than just the bytes. You'll need meta-data associated with the file. For the snippet below, I've placed all of that metadata into a separate class (local instance named "file"). Then, just use this snippet, once you have the data you need:

    Response.Clear();
    Response.ClearHeaders();
    Response.ContentType = file.ContentType;
    Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.FileName + "\"");
    Response.AddHeader("Content-Length", file.FileSize.ToString());
    Response.OutputStream.Write(file.Bytes, 0, file.Bytes.Length);
    Response.Flush();
    Response.End();
    

提交回复
热议问题