Triggering a file download without any server request

前端 未结 4 1321
粉色の甜心
粉色の甜心 2020-12-06 05:43

Greetings,

I\'m working on a JS-based application that does some complex work and logs some information (actually, up to hundreds of lines) on a

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 06:30

    This solution is slightly convoluted but would work for your needs, perhaps it's an option.

    Create a custom web server that simply returns the contents of any GET or POST as text/plain.

    Host that web server on the same box as the web application but running on a different port. When you click the Save log button, the request is sent to the custom server and the text file is returned.

    Here's a proof of concept server in Java that will do just that:

    // After running this program, access with your browser at 127.0.0.1:8080
    
    import java.net.*;
    import java.io.*;
    
    public class ReturnTextFile
    {
    
        public static void main(String[] args)
        {
    
        try
        {
            ServerSocket server = new ServerSocket(8080);
            Socket connection = null;
    
            while (true)
            {
    
            try
            {
                connection = server.accept();
    
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
                String input = in.readLine();
    
                // TODO: Clean up input
    
                Writer out = new OutputStreamWriter(connection.getOutputStream());
    
                String output = "HTTP/1.1 200 OK\n" +
                        "Connection: close\n" +
                        "Content-Disposition: attachment; filename=log.txt\n" +
                        "Content-Type: text/plain; charset=utf-8\n" +
                        "\n";
    
                output += input;
    
                out.write(output);
    
                out.flush();
    
                connection.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
            finally
            {
                if (connection != null)
                {
                connection.close();
                }
            }
    
            }
    
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    
        }
    }
    

提交回复
热议问题