从 javascript 从本地文件系统获取图像

get an image from local filesystem from javascript

我正在尝试将图像存储到本地文件系统中。之后,我需要使用来自 javascript.

的图像安装一个 html

到目前为止,我正在使用 servlet 获取图像,它实际上可以正常工作,因为我可以在我的 JSP <img width="120" src="<%=IncVars.getParameter("ruta0")%>myImageServlet">

中显示图像
public class MyImageServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    //get the file image
    File image = IncFunctions.getLogoFile();

    // Get content type
    String contentType = getServletContext().getMimeType(image.getName());

    // Init servlet response.
    response.reset();
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(image.length()));
    // Write image content to response.
    Files.copy(image.toPath(), response.getOutputStream());
}
//...
}

我正在尝试做同样的事情来从 js 函数挂载 html,但我找不到在我的 js 函数中使用此图像生成 html 的方法:

 function mountTicket(text, idControl, servletPath){
     document.getElementById(idControl).innerHTML = parseTicket(texto, imagePath);
     window.print();
 }

function parseTicket(texto, servletPath){

var textHtml = "";

 //Call the servlet
 $.get(servletPath, function(data) {
     textoHtml = "<img  width='120' src=" + data + "/>";
     textoHtml += "<br />";
 });    

  //..


  textoHtml += "<div";
  if (estilo != ""){
  textoHtml += " style=\"" + estilo + "\"";
  }         

  textoHtml += ">" + contenido + "</div>";  

  return textoHtml;
}

从servlet获取的data var是bytes,js好像不知道怎么解释。我也尝试过传递图像的路径,比方说"C:\myDirectory\myImage.png",但正如我所料,它找不到并显示它。

如有任何帮助,我们将不胜感激。提前致谢。

答案比我想象的要简单。我不需要从我的 js 代码调用 servlet,我只需要添加带有 servlet 路径的图像。 像这样:

textoHtml  = "<div><img src='" + servletPath + "'> </div>" ;

浏览器会显示图像。

希望对有类似情况的人有所帮助"issues"