我们有一个非常简化的API,可根据请求发送文件
服务器是:
public class Server {
public static void main(String... args) throws Exception {
// start the server
System.out.println("starting jetty...");
final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(80);
server.setHandler(new Handler());
server.start();
System.out.println("jetty server has started");
}
}
和处理程序:
public class Handler extends AbstractHandler {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
if(target.matches("/get")){
File file = getFile(); //assume filename is myFile.zip
byte[] bytes = FileUtils.readFileToByteArray(file);
response.getOutputStream().write(bytes);
response.flushBuffer();
}
}
}
当我从浏览器向localhost:80/get
发出请求时,会保存所需的文件,但浏览器会将其命名为get
需要进行哪些更改,以便请求将文件保存为myFile.zip
?
答案 0 :(得分:2)
您可以添加如下文件名:
response.setHeader("Content-Disposition", "filename=myFile.xyz");
如果您希望浏览器打开保存对话框,请添加附件:
response.setHeader("Content-Disposition", "attachment; filename=myFile.xyz");