您可以使用表单面板进行上传,表单面板将使用隐藏的 iframe,
FormPanel form = new FormPanel();
form.setMethod(FormPanel.METHOD_POST);
form.setAction("/downloadServlet");
FlowPanel hiddenPanel = new FlowPanel();
hiddenPanel.add(new Hidden("name1", "value"));
hiddenPanel.add(new Hidden("name2", "value"));
form.setWidget(hiddenPanel);
RootPanel.get().add(form);
form.submit();
如果您放置了正确的标头,则 servlet 返回的内容将由用户导航器下载。
public class ServletDownloadDemo extends HttpServlet{
private static final int BYTES_DOWNLOAD = 1024;
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException{
//Get Parameters
String name1 = request.getParameter("name1");
String name2 = request.getParameter("name2");
response.setContentType("text/plain");
response.setHeader("Content-Disposition",
"attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/testing.txt");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}