Servlet java,服务器端,发送一个字符串作为新的txt文件

时间:2013-10-08 07:24:53

标签: java servlets

我有一个Java Web应用程序。用户可以上传文件(通过POST请求),然后servlet将在该文件上执行一些代码。此代码的输出是一个字符串。

如何在不在服务器端创建文件的情况下将文件返回给用户?这可能吗?

2 个答案:

答案 0 :(得分:1)

是,     你必须设置内容处理标题,然后将流写入响应。

答案 1 :(得分:0)

尝试使用该代码

package com.hainasoft.web;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    private static final int BUFSIZE = 4096;
    private String filePath;

    public void init() {
        // the file data.xls is under web application folder
        filePath = getServletContext().getRealPath("") + File.separator + "data.xls";
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        File file = new File(filePath);
        int length   = 0;
        ServletOutputStream outStream = response.getOutputStream();
        ServletContext context  = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(filePath);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";
        }
        response.setContentType(mimetype);
        response.setContentLength((int)file.length());
        String fileName = (new File(filePath)).getName();

        // sets HTTP header
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        byte[] byteBuffer = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while ((in != null) && ((length = in.read(byteBuffer)) != -1))
        {
            outStream.write(byteBuffer,0,length);
        }

        in.close();
        outStream.close();
    }
}

设置myme类型

非常重要
mimetype = "application/octet-stream";

并使用此功能为用户设置下载对话框

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

我从中检索了所有这些信息 http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html

所以请查看更准确的信息。