Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用html2canvas上传屏幕截图?_Javascript_Ajax_Upload_Screenshot_Html2canvas - Fatal编程技术网

Javascript 如何使用html2canvas上传屏幕截图?

Javascript 如何使用html2canvas上传屏幕截图?,javascript,ajax,upload,screenshot,html2canvas,Javascript,Ajax,Upload,Screenshot,Html2canvas,使用如何将屏幕快照保存到对象?我一直在探索演示,看到生成屏幕截图的函数如下所示: $(window).ready(function() { ('body').html2canvas(); }); 我试着做的是 $(window).ready(function() { canvasRecord = $('body').html2canvas(); dataURL = canvasRecord.toDataURL("image/png"); dataURL = da

使用如何将屏幕快照保存到对象?我一直在探索演示,看到生成屏幕截图的函数如下所示:

$(window).ready(function() {
  ('body').html2canvas();       
});
我试着做的是

$(window).ready(function() {
  canvasRecord = $('body').html2canvas(); 
  dataURL = canvasRecord.toDataURL("image/png");
  dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  upload(dataURL);

});
然后,我将其传递给我的
upload()
函数。我遇到的问题是,我无法确定在
html2canvas()
库中的屏幕截图是在哪里制作的,或者是哪个函数返回它。我尝试过使用SO的答案转换画布对象(尽管我不确定是否需要这样做)


我只是问了一个关于如何上传文件的问题,那里的答案(特别是@bebraw的)帮助我理解我需要做什么

upload()
函数来自Imgur示例api帮助:

function upload(file) {
   // file is from a <input> tag or from Drag'n Drop
   // Is the file an image?
   if (!file || !file.type.match(/image.*/)) return;

   // It is!
   // Let's build a FormData object
   var fd = new FormData();
   fd.append("image", file); // Append the file
   fd.append("key", "mykey"); // Get your own key: http://api.imgur.com/

   // Create the XHR (Cross-Domain XHR FTW!!!)
   var xhr = new XMLHttpRequest();
   xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
   xhr.onload = function() {
      // Big win!
      // The URL of the image is:
      JSON.parse(xhr.responseText).upload.links.imgur_page;
   }

   // Ok, I don't handle the errors. An exercice for the reader.
   // And now, we send the formdata
   xhr.send(fd);
}
函数上传(文件){
//文件来自标记或拖放
//文件是图像吗?
如果(!file | |!file.type.match(/image.*/)返回;
//是的!
//让我们构建一个FormData对象
var fd=新FormData();
fd.append(“image”,file);//追加文件
fd.append(“key”、“mykey”);//获取您自己的密钥:http://api.imgur.com/
//创建XHR(跨域XHR FTW!!!)
var xhr=new XMLHttpRequest();
xhr.open(“POST”http://api.imgur.com/2/upload.json);//嘘!
xhr.onload=函数(){
//大胜利!
//图像的URL为:
parse(xhr.responseText).upload.links.imgur\u页面;
}
//好的,我不处理这些错误。这是给读者的练习。
//现在,我们发送表单数据
xhr.send(fd);
}

我已从中修改并注释了该方法。它只发送一个由
元素组成的具有给定名称的文件

if (!('sendAsBinary' in XMLHttpRequest.prototype)) {
  XMLHttpRequest.prototype.sendAsBinary = function(string) {
    var bytes = Array.prototype.map.call(string, function(c) {
      return c.charCodeAt(0) & 0xff;
    });
    this.send(new Uint8Array(bytes).buffer);
  };
}

/*
 * @description        Uploads a file via multipart/form-data, via a Canvas elt
 * @param url  String: Url to post the data
 * @param name String: name of form element
 * @param fn   String: Name of file
 * @param canvas HTMLCanvasElement: The canvas element.
 * @param type String: Content-Type, eg image/png
 ***/
function postCanvasToURL(url, name, fn, canvas, type) {
  var data = canvas.toDataURL(type);
  data = data.replace('data:' + type + ';base64,', '');

  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  var boundary = 'ohaiimaboundary';
  xhr.setRequestHeader(
    'Content-Type', 'multipart/form-data; boundary=' + boundary);
  xhr.sendAsBinary([
    '--' + boundary,
    'Content-Disposition: form-data; name="' + name + '"; filename="' + fn + '"',
    'Content-Type: ' + type,
    '',
    atob(data),
    '--' + boundary + '--'
  ].join('\r\n'));
}

这个代码对我有用。它将通过html2canvas生成屏幕截图,将屏幕截图上传到imgur api,并返回imgur url

<button class="upload" >Upload to Imgur</button> 
<script>
$(".upload").on("click", function(event) {
    html2canvas($('body'), {
  onrendered: function(canvas) {
  document.body.appendChild(canvas);
      try {
      var img = canvas.toDataURL('image/jpeg', 0.9).split(',')[1];
  } catch(e) {
      var img = canvas.toDataURL().split(',')[1];
  }
  // open the popup in the click handler so it will not be blocked
  var w = window.open();
  w.document.write('Uploading...');
  // upload to imgur using jquery/CORS
  // https://developer.mozilla.org/En/HTTP_access_control
  $.ajax({
      url: 'http://api.imgur.com/2/upload.json',
      type: 'POST',
      data: {
          type: 'base64',
          // get your key here, quick and fast http://imgur.com/register/api_anon
          key: 'your api key',
          name: 'neon.jpg',
          title: 'test title',
          caption: 'test caption',
          image: img
      },
      dataType: 'json'
  }).success(function(data) {
      w.location.href = data['upload']['links']['imgur_page'];
  }).error(function() {
      alert('Could not reach api.imgur.com. Sorry :(');
      w.close();
  });
  },
  });
  });
</script>
上传到Imgur
$(“.upload”)。在(“单击”上,函数(事件){
html2canvas($('body'){
onrendered:函数(画布){
document.body.appendChild(画布);
试一试{
var img=canvas.toDataURL('image/jpeg',0.9).split(',')[1];
}捕获(e){
var img=canvas.toDataURL().split(',')[1];
}
//在单击处理程序中打开弹出窗口,使其不会被阻止
var w=window.open();
w、 文件。写入('上传…');
//使用jquery/CORS上传到imgur
// https://developer.mozilla.org/En/HTTP_access_control
$.ajax({
网址:'http://api.imgur.com/2/upload.json',
键入:“POST”,
数据:{
键入:“base64”,
//快,快,把钥匙拿过来http://imgur.com/register/api_anon
密钥:“您的api密钥”,
名称:“neon.jpg”,
标题:'测试标题',
标题:“测试标题”,
图片:img
},
数据类型:“json”
}).成功(功能(数据){
w、 location.href=data['upload']['links']['imgur_page'];
}).错误(函数(){
警报('无法访问api.imgur.com。抱歉:(');
w、 close();
});
},
});
});
//在这里,我使用html2Canvas捕获屏幕,并使用Java WebSocket将数据传输到服务器
//限制:最新浏览器和Tomcat支持
步骤1)客户端:webSock.html
>
Tomcat web套接字
var ws=new-WebSocket(“ws://localhost:8080/WebSocketSample/wsocket”);
ws.onopen=函数(){
log(“Web套接字打开”);
};
ws.onmessage=函数(消息){
日志(“来自服务器的消息:+message.data”);
//document.getElementById(“msgArea”).textContent+=message.data+“\n”;
document.getElementById(“msgArea”).textContent+“数据发送\n”;
};
函数postToServerNew(数据){
send(JSON.stringify(data));
document.getElementById(“msg”).value=“”;
}
//设定间隔
setInterval(函数(){
var目标=$('body');
html2canvas(目标{
onrendered:函数(画布){
var data=canvas.toDataURL();
var jsonData={
键入:“视频”,
数据:数据,
持续时间:5,
时间戳:0,//在工作进程中设置
currentFolder:0,//在辅助进程中设置
}; 
postToServerNew(jsonData);
}
});
},9000);
函数closeConnect(){
ws.close();
log(“Web套接字关闭:再见TC”);
}
发送消息
步骤2)服务器端
文件1)
包装工程;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.RandomAccessFile;
导入java.nio.ByteBuffer;
导入java.nio.CharBuffer;
导入java.nio.MappedByteBuffer;
导入java.nio.channels.AsynchronousFileChannel;
导入java.nio.channels.FileChannel;
导入java.nio.charset.charset;
导入java.nio.file.path;
导入java.nio.file.StandardOpenOption;
导入java.util.concurrent.ExecutionException;
导入java.util.concurrent.Future;
导入javax.servlet.http.HttpServletRequest;
导入org.apache.catalina.websocket.MessageInbound;
导入org.apache.catalina.websocket.WsOutbound;
/**
*类路径上需要tomcat-koyote.jar,否则会出现编译错误
*“类型的层次结构…不一致”
* 
*@作者阿伦
* 
*/
公共类MyInBound扩展了MessageInbound{
私有字符串名称;
私家车出站;
私有字符串目标定位;
公共MyInBound(HttpServletRequestHttpServletRequest,字符串targetLocation){
this.targetLocation=targetLocation;
}
@凌驾
公共无效onOpen(WsOutbound-outbound){
System.out.println(“打开的Web套接字”);
/*this.myoutbound=出站;
试一试{
this.myoutbound.writeTextMessage(CharBuffer.wrap(“打开的Web套接字”);
}捕获(例外e){
抛出新的运行时异常(e);
}*/
}
@凌驾
公共void onClose(int状态){
System.out.println(“关闭客户端”);
//从列表中删除
}
@凌驾
受保护的void onBinaryMessage(ByteBuffer arg0)引发IOException{
System.out.println(“onBinaryMessage数据”);
试一试{
writeToFileNIOWay(新文件(targetLocation),arg0.t
//Here I am using html2Canvas to capture screen and Java websockets to transfer data to server
//Limitation:Supported on latest browsers and Tomcat
Step1)Client Side : webSock.html  
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- Arun HTML File -->>
<html>
<head>
<meta charset="utf-8">
<title>Tomcat web socket</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
<script type="text/javascript" src="html2canvas.js?rev032"></script> 
<script type="text/javascript"> 
var ws = new WebSocket("ws://localhost:8080/WebSocketSample/wsocket");
ws.onopen = function () {
    console.log("Web Socket Open");
};

   ws.onmessage = function(message) {
       console.log("MSG from Server :"+message.data);
//document.getElementById("msgArea").textContent += message.data + "\n";    
document.getElementById("msgArea").textContent +" Data Send\n";    
   };
 function postToServerNew(data) {
ws.send(JSON.stringify(data));
document.getElementById("msg").value = "";
}

//Set Interval
setInterval(function(){
 var target = $('body');
   html2canvas(target, {
     onrendered: function(canvas) {
     var data = canvas.toDataURL();
  var jsonData = {
        type: 'video', 
        data: data, 
        duration: 5 , 
        timestamp: 0,   // set in worker
        currentFolder: 0,// set in worker
    }; 
postToServerNew(jsonData);
   }
 });
},9000);

function closeConnect() {
ws.close();
console.log("Web Socket Closed: Bye TC");
}
</script>
</head>

<body>
  <div>
<textarea rows="18" cols="150" id="msgArea" readonly></textarea>
</div>
<div>
<input id="msg" type="text"/>
<button type="submit" id="sendButton" onclick="postToServerNew('Arun')">Send MSG</button>
</div>
</body>
</html>

Step2)Server Side   
File 1)   
package Arun.Work;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

/**
 * Need tomcat-koyote.jar on class path, otherwise has compile error
 * "the hierarchy of the type ... is inconsistent"
 * 
 * @author Arun
 * 
 */
public class MyInBound extends MessageInbound {

    private String name;

    private WsOutbound myoutbound;

    private String targetLocation;

    public MyInBound(HttpServletRequest httpSerbletRequest, String targetLocation) {
        this.targetLocation = targetLocation;
    }

    @Override
    public void onOpen(WsOutbound outbound) {
        System.out.println("Web Socket Opened..");
        /*this.myoutbound = outbound;
        try {
            this.myoutbound.writeTextMessage(CharBuffer.wrap("Web Socket Opened.."));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }*/

    }

    @Override
    public void onClose(int status) {
        System.out.println("Close client");
        // remove from list
    }

    @Override
    protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
        System.out.println("onBinaryMessage Data");
        try {
            writeToFileNIOWay(new File(targetLocation), arg0.toString() + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //this.myoutbound.flush();
        }
    }// end of onBinaryMessage

    @Override
    protected void onTextMessage(CharBuffer inChar) throws IOException {
        System.out.println("onTextMessage Data");
        try {

            writeToFileNIOWay(new File(targetLocation), inChar.toString() + "\n");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //this.myoutbound.flush();
        }
    }// end of onTextMessage

    public void writeToFileNIOWay(File file, String messageToWrite) throws IOException {
        System.out.println("Data Location:"+file+"            Size:"+messageToWrite.length());
        //synchronized (this){

          byte[] messageBytes = messageToWrite.getBytes();
          RandomAccessFile raf = new RandomAccessFile(file, "rw");
          raf.seek(raf.length());
          FileChannel fc = raf.getChannel();
          MappedByteBuffer mbf = fc.map(FileChannel.MapMode.READ_WRITE, fc.position(), messageBytes.length);
          mbf.put(messageBytes);
         fc.close();
        //}


    }//end of method

    /*
     * //Working Fine public void writeToFileNIOWay(File file, String
     * messageToWrite) throws IOException { byte[] messageBytes =
     * messageToWrite.getBytes(Charset.forName("ISO-8859-1")); RandomAccessFile
     * raf = new RandomAccessFile(file, "rw"); raf.seek(raf.length());
     * FileChannel fc = raf.getChannel(); MappedByteBuffer mbf =
     * fc.map(FileChannel.MapMode.READ_WRITE, fc.position(),
     * messageBytes.length);
     * 
     * mbf.put(messageBytes); fc.close(); }
     */
}


File 2)     
package Arun.Work;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

/**
 * WebSocketServlet is contained in catalina.jar. It also needs servlet-api.jar
 * on build path
 * 
 * @author Arun
 * 
 */
@WebServlet("/wsocket")
public class MyWebSocketServlet extends WebSocketServlet {

    private static final long serialVersionUID = 1L;

    // for new clients, <sessionId, streamInBound>
    private static ConcurrentHashMap<String, StreamInbound> clients = new ConcurrentHashMap<String, StreamInbound>();

    @Override
    protected StreamInbound createWebSocketInbound(String protocol, HttpServletRequest httpServletRequest) {

        // Check if exists
        HttpSession session = httpServletRequest.getSession();

        // find client
        StreamInbound client = clients.get(session.getId());
        if (null != client) {
            return client;

        } else {
            System.out.println(" session.getId() :"+session.getId());
            String targetLocation = "C:/Users/arsingh/Desktop/AnupData/DATA/"+session.getId();
            System.out.println(targetLocation);
            File fs=new File(targetLocation);
            boolean bool=fs.mkdirs();
            System.out.println(" Folder created :"+bool);
            client = new MyInBound(httpServletRequest,targetLocation+"/Output.txt");
            clients.put(session.getId(), client);
        }

        return client;
    }

    /*public StreamInbound getClient(String sessionId) {
        return clients.get(sessionId);
    }

    public void addClient(String sessionId, StreamInbound streamInBound) {
        clients.put(sessionId, streamInBound);
    }*/
}