我有一个 Java 网络应用程序。用户可以上传一个文件(通过 POST 请求),然后 servlet 将在这个文件上执行一些代码。此代码的输出是一个字符串。
如何将文件返回给用户,而不在服务器端创建文件?那可能吗?
是的,您必须设置内容处置标头,然后将流写入响应。
尝试使用该代码
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 + "\"");
因此,请查看它以获取更准确的信息。