Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Prompt file download

I have a link on my page on click of which I am trying to generate a PDF document and then show the "Open - Save" prompt on the browser.

My HTML (reactjs component) has the below code where onclick calls the _getMyDocument function which then calls a Webapi method.

 <div className="row">
     <a href="#" onClick={this._getMyDocument.bind(this)}>Test Link</a>
 </div>  

_getMyDocument(e) {
            GetMyDocument(this.props.mydata).then(()=> {
   }).catch(error=> {

  });

My Controller has the below code

[HttpPost]
[Route("Generate/Report")]
public IHttpActionResult GetMyReport(MyData myData)
 {  
    byte[] myDoc = MyBusinessObject.GenerateMyReport(myData);
    var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(myDoc)
        };
        result.Content.Headers.ContentDisposition =
            new ContentDispositionHeaderValue("attachment")
            {
                FileName = "MyDocument.pdf"
            };
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");

        var response = ResponseMessage(result);

        return response;
  }

Currently all the code executes but I don't get the file PDF download prompt. What am I doing wrong here?

Response object on success from the ajax call lokks like below

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your response from the server looks good. The missing part is that you are not handling this response from the client side in the correct way.

Lets assume that your resource url object looks like below in js. (i.e. you already know the resource url, if you don't know it yet, then you will need a separate call to the server to know the download url)

response.downloadUrl = app/media/fileId/document.pdf

All you need to do is set,

window.location = item.downloadUrl;

This will cause the browser to request a resource from the server, the response from the server must include Content-Disposition:attachment;. It will cause the browser to show the download dialog.

P.S. I have recently worked on a similar functionality. If you have questions please ask.

When you want to force the browser to show the download prompt for some files (or resources), you must include Content-Disposition:attachment; in the response header (which you already did).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...