简体   繁体   中英

Dragging out a .zip file to download

I am creating a .zip file with node.js (using nw.js ), then sending the path to the generated file to the front-end. I want the user to be able to drag the HTML element from the nw.js window to his desktop and change it to the .zip file on drop (checkout a simple example with another file type here ).

I know I can use the dataTransfer property and set the data type to application/zip , but I don't know how to send the .zip file data with this method.

React = require "react"

module.exports = React.createClass
    onDragStart : ( event ) ->
        event.dataTransfer.setData "application/zip:#{@props.path}"

    render : ->
        <div draggable="true" onDragStart={@onDragStart}>Download</div>

I guess I should create a stream for the .zip file but I have no idea how. I have access to the fs module, even on the "client" side, so there are no limits. Any thoughts of how can I achieve that effect?

I figured out how to make it work. It was not working because I was trying to download a local file, so I created a temporary HTTP Server which returns the .zip file on every request with the MIME type set to application/zip . Then I just have to set the data transfer URL to http://localhost:3000 and voila.

Here's the code:

fs      = require "fs"
http    = require "http"
React   = require "react"

module.exports = React.createClass
    componentWillMount : ->
        index  = fs.readFileSync @props.path
        server = http.createServer ( request, response ) =>
            response.writeHead 200, { "Content-Type" : "application/zip" }
            response.end index

        server.listen 3000

    onRequestDownload : ( event ) ->
        event.dataTransfer.setData "DownloadURL", "application/zip:FileName.zip:http://localhost:3000"

    render : ->
        <div className="view download">
            <div className="download-item" draggable="true" onDragStart={@onRequestDownload}>Download</div>
        </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM