【问题标题】:GWT doGet() servlet return image byte array or image to clientGWT doGet() servlet 将图像字节数组或图像返回给客户端
【发布时间】:2019-01-02 21:59:59
【问题描述】:

我正在使用 GWT 文件上传小部件上传图像,然后使用 http servlet 将图像导入数据库。

我正在使用 formPanel FormPanel.METHOD_GET 来调用我的servelet doGet(),我正在获取图像并将其存储到字节数组中。我不确定如何将其返回给客户?

客户端代码

downloadPanel = new FormPanel();
downloadPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
downloadPanel.setMethod(FormPanel.METHOD_GET);
downloadPanel.setAction(GWT.getModuleBaseURL()+"downloadfile" + "?brandID="+ accountIdStr);
downloadPanel.submit();

downloadPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            @Override
            public void onSubmitComplete(FormPanel.SubmitCompleteEvent submitCompleteEvent) {

                image.setUrl(" http://www.tutorialspoint.com/images/gwt-mini.png");

               // image.setUrl(submitCompleteEvent.getResults());
                Window.alert(submitCompleteEvent.getResults());

            }
        });

服务器代码

public class FileDownload extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    UserAccount adminUserAccount = getAdminUserAccount(request);
    int accountId = adminUserAccount.getAccountID();

    byte[] b =  API.GetAccountManager().getCompanyLogo(accountId);

字节数组中包含图像。如何将字节数组或图像返回给客户端?

【问题讨论】:

    标签: java gwt


    【解决方案1】:

    使用响应 Writer 将响应写回客户端,如下所示:

    byte[] b =  API.GetAccountManager().getCompanyLogo(accountId);
    respose.getOutputStream().write(b);
    

    它将字节写回客户端,在客户端,您需要解析最有可能来自InputStream的字节。

    【讨论】:

    • 它不会让我只将字节数组作为字符串发送
    • @piddler 你是对的,前面的例子是String,不是byte[],我的错。编辑答案以使用getOutputStream(),而不是getWriter()。它的 write 方法接受 byte[]
    • 我从字符串中提取了 url,我在浏览器上看到了图像。谢谢
    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多