加载和重用图像源(blob)

时间:2018-07-22 18:06:41

标签: javascript java html jetty

我有一个客户端服务器应用程序,需要从服务器中加载图片。我正在使用此处介绍的访存方法-https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data

它工作得很好,我可以将我的图片放在无序列表中。

重点是,我需要重用先前加载的图像源,以用相同的图像提供新列表。但是,新列表中什么也没有显示,在检查控制台时,我们可以看到新图像的src是“未知”。

谢谢!

这是我的密码

服务器(带有Jetty服务器的Java)

import javax.servlet.Servlet;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletHandler;

public class MyServer 
{
    public static void main(String[] args) 
    {
        Server server = new Server(8001);

        ServletHandler spriteSerialize = new ServletHandler();
        spriteSerialize.addServletWithMapping(MyJSONSender.class, "/json");
        spriteSerialize.addServletWithMapping(MyImages.class, "/imgs");

        ResourceHandler resource_handler = new ResourceHandler();
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]
                { 
                        "WAR/views/entryPoint.html",
                });
        resource_handler.setResourceBase(".");

        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] {resource_handler, spriteSerialize});
        server.setHandler(handlers);

        try {
            server.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            server.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

服务器(辅助类MyJSONSender)

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class MyJSONSender extends HttpServlet
{
     @Override
        protected void doGet( HttpServletRequest request,
                              HttpServletResponse response ) throws ServletException,
                                                            IOException
        {
            JSONArray array = new JSONArray();

            JSONObject obj1 = new JSONObject();
            obj1.put("name", "axeman");
            obj1.put("img", "oryx/axeman1.png");
            JSONObject obj2 = new JSONObject();
            obj2.put("name", "alien1");
            obj2.put("img", "oryx/alien1.png");
            JSONObject obj3 = new JSONObject();
            obj3.put("name", "barrel1");
            obj3.put("img", "oryx/barrel1.png");

            array.add(obj1); array.add(obj2); array.add(obj3);

            String toSend = array.toJSONString();

            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(toSend);
        }
}

服务器(辅助类MyImages)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class MyImages extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String imageToServe = req.getParameter("picture");
        System.out.println(imageToServe);

        Path path = Paths.get("sprites/" + 
                imageToServe);
        byte[] data = Files.readAllBytes(path);

        resp.setContentType("image/png");
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getOutputStream().write(data);
    }

}

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Images</title>
</head>
<body>
<h1>IMAGES</h1>

<ul id="imageList"></ul>

<ul id="horizontalImageList"></ul>

<script src="load.js"></script>

</body>
</html>

JS

var xmlhttp = new XMLHttpRequest();

var spriteSetObj;

function buildTheSpriteSet(spriteSetObj) {

    var ulElement = document.getElementById('imageList');

    for (var i = 0; i < spriteSetObj.length; i++) {
        getObjectData(spriteSetObj[i], ulElement);
    }

    fillHorizontalList(spriteSetObj);
}

xmlhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        spriteSetObj = JSON.parse(this.responseText);
        console.log(spriteSetObj);
        buildTheSpriteSet(spriteSetObj);
    }
};

xmlhttp.open("GET", "http://localhost:8001/json", true);
xmlhttp.send();

function getObjectData(spriteSet, upperUl)
{
    var li = document.createElement("li");
    li.innerHTML = spriteSet['name'];
    upperUl.appendChild(li);

    var img = document.createElement('img');
    img.id = spriteSet['name'];
    fetchBlob(spriteSet['img'], img);

    upperUl.appendChild(img);
}

function fillHorizontalList(spriteSet)
{
    var ulHorizontalElement = document.getElementById('horizontalImageList');
    for(var i = 0; i < spriteSet.length; i++)
    {
        var img = document.createElement('img');
        img.src = document.getElementById(spriteSet[i].name).src;
        ulHorizontalElement.append(img);
    }
}

function fetchBlob(imgPath, imgElement) {
    // construct the URL path to the image file from the product.image property
    var urlSrc = null;
    // Use XHR to fetch the image, as a blob
    // Again, if any errors occur we report them in the console.
    var request = new XMLHttpRequest();
    var params = "picture=" + imgPath;
    request.open('GET', "http://localhost:8001/imgs" + "?" + params, true);
    request.responseType = 'blob';
    var objectURL = null;

    request.onload = function() {
        if(request.status === 200) {
            // Convert the blob to an object URL — this is basically an temporary internal  URL
            // that points to an object stored inside the browser
            var blob = request.response;
            objectURL = URL.createObjectURL(blob);
            // invoke showProduct
            imgElement.src = objectURL;

        } else {
            alert('Network request for "' + product.name + '" image failed with response ' +     request.status + ': ' + request. statusText);
        }
    };

    request.send();
}

0 个答案:

没有答案