Angular2 display file download link






















You can have a look for more details on response type. I have used three ways for downloading file — two ways for Save as functionality and one way to show the file content on browser itself.

The above line create a Blob object with file content in response and expecting the file of JSON type. The above two lines create a URL that will open the file in browser in new window.

The above line shows the file content on browser, so it does not give you save as option. The above line uses ready-made FileSaver module that will open the file with Save as option. I have created service class to fetch file data from a server URL but I need to provide a link or button for downloading the file.

In the view file I will give users two options for downloading the same file. I will use link as well as button for downloading the same file from the server. In the service class I have used Http module which may not be found automatically. So I need to register it in providers array of NgModule. Run the Angular application angular-file-download by executing command ng serve --open.

We are going to add a few more elements to the UI of our file upload component. Here is the final version of the file upload component template:. With this feature, we can get notified of the progress of a file upload via multiple events emitted by the HTTP Observable. To see it in action, let's have a look at the final version of the file upload component class, with all its features implemented:. As we can see, we have set the reportProgress property to true in our HTTP call, and we have also set the observe property to the value events.

Using the events of type UploadProgress , we are saving the ongoing upload percentage in a member variable uploadProgress , which we then use to update the value of the progress indicator bar.

We can make sure that we do so by using the RxJs finalize operator, which is going to call the reset method in both cases: upload success or failure.

In our component, we store this subscription object in the uploadSub member variable. While the upload is still in progress, the user might decide to cancel it by clicking on the cancel button. Then the cancelUpload upload method is going to get triggered and the HTTP request can be canceled by unsubscribing from the uploadSub subscription.

In the final version of our file upload component, we can require the user to upload a file of a certain type, by using the requiredFileType property:. This property is then passed directly to the accept property of the file input in the file upload template, forcing the user to select a png file from the file upload dialog.

By default, the browser file selection dialog will allow the user to select only one file for upload. But using the multiple property, we can allow the user to select multiple files instead:.

Notice that this would need a completely different UI than the one that we have built. A styled upload button with a progress indicator only works well for the upload of a single file. For a multi-file upload scenario, there are a variety of UIs that could be built: a floating dialog with the upload progress of all files, etc. The way that you handle the uploaded file in your backend depends on the technology that you use, but let's give a quick example of how to do it if using Node and the Express framework.

We need to first install the express-fileupload package. We can then add this package as a middleware in our Express application:. This way we can access event-specific fields in a type-safe way. They both contain the discriminator field type allowing us to easily return a boolean for the type assertion in our guards.

The guards can be used with a simple if-statement, however, TypeScript will narrow the event type inside the statement block for us:. Based on these guards we can now create our custom operator. It'll leverage scan , an operator that allows us to accumulate state for successive values coming through an observable.

It takes up to two arguments: First, we provide an accumulator function which will compute the next Download state from the previous one and the current HttpEvent.

Second, we'll pass a seed to scan representing the initial Download state. This seed will represent our download being pending without any progress or content:. Our accumulator will use the previously defined guard to update the Download state over time with information from the HTTP events:. When we encounter a HttpProgressEvent , we calculate the progress based on the number of bytes already loaded and the total bytes. A download is done when we receive a HttpResponse containing the file contents in its body.

When receiving any other events than HttpProgressEvent or HttpResponse , we won't alter the download's state and return it as it is. This way, for example, we can keep the information in the progress property while other events that won't allow us to compute the progress can be ignored for now. Anything unclear? Let's finally define our custom operator that's using scan with our accumulator and seed :. Notice that this download operator accepts an optional parameter saver.

Once a HTTP response is received, this function is invoked with the download content from inside the accumulator. This allows us to pass in a strategy for persisting the download to a file without directly coupling the operator to FileSaver. By keeping FileSaver. The download operator can be tested without somehow mocking the saveAs import see here for corresponding tests. This should be the answer -- it allowed me to use authorization on the get without having to extend Xhr and worked just as well as the top answer.

What is this 'saveAs' function here? If it is github. Can you include the imports that you've used? Here is the simplest way to download a file from an API that I was able to come up with. Shashank Shekhar Shashank Shekhar 3, 2 2 gold badges 39 39 silver badges 50 50 bronze badges.

Types of property 'responseType' are incompatible. Type 'ResponseContentType' is not assignable to type '"json"'. BenDonnelly It should be this. Thom Kiesewetter Thom Kiesewetter 4, 2 2 gold badges 22 22 silver badges 33 33 bronze badges. Note: http call from client needs to support blob response.

Dilip Nannaware Dilip Nannaware 1, 1 1 gold badge 14 14 silver badges 23 23 bronze badges. CreateResponse HttpStatusCode. OK ; result. ElliotSchmelliot ElliotSchmelliot 5, 3 3 gold badges 36 36 silver badges 61 61 bronze badges. Eylon Sultan Eylon Sultan 8 8 silver badges 14 14 bronze badges.

Please add some description so that the original poster can learn from you. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Benehiko Benehiko 3 3 silver badges 6 6 bronze badges. The Overflow Blog. Who owns this outage? Building intelligent escalation chains for modern SRE. Podcast Who is building clouds for the independent developer? Featured on Meta. Now live: A fully responsive profile.



0コメント

  • 1000 / 1000