Download file from webservice - in ASP.NET site

后端 未结 4 2349
没有蜡笔的小新
没有蜡笔的小新 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:10

    Its usually a bad idea to embed a file in a web service. You just add overhead and complexity with no real benefit.

    Instead you should provide a IHttpHandler to handle the file upload. Most web servers also provide helper API's to simplify this, e.g. in ASP.NET you can access the uploaded file with:

    HttpContext.Request.Files[0]

    There are plenty of javascript file upload scripts that simplify this on the client: http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

    0 讨论(0)
  • 2021-02-20 14:12

    It's possible, you'll need to make sure you explicitly set the ContentType of the HttpResponse, for example:

    Response.ContentType = "image/jpeg";
    Response.OutputStream.Write(buffer, 0, buffer.Length);
    

    If you want to control the file name, you'll have to add a Content-Disposition header. Google can help you find the right way to sort that out.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2021-02-20 14:27

    It really depends on the interface to your webservice. Ie SOAP, REST, ASPX.

    One thing you can try is to change the content-type in your Response to "Application/octet-stream". Or something similar to tell the receiver the MIME type.

    If your using WCF rest you can use Stream as a return type on the web service.

    0 讨论(0)
提交回复
热议问题