我正在尝试使用cefsharp winforms从我的应用程序下载一些文件(图像,文件音频或其他内容)。我读了其他任何帖子,但似乎没什么用。 你有任何示例代码可以告诉我实现cefsharp的下载器吗?
当然,当我现在尝试下载一些文件时,没有任何反应。
由于
答案 0 :(得分:11)
要解决此问题,只需下载找到的DownloadHandler.cs类 here.
之后,将其导入Visual Studio项目,并将此行添加到主窗体的代码中: package com;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class PahoDemo implements MqttCallback {
MqttClient client;
static String clientMessage="";
static String topic="";
static String ipAddress="";
static Scanner scan = new Scanner(System.in);
static byte[] compressedMessage;
public PahoDemo() {
}
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
new PahoDemo().setDetails(args[0], args[1],args[2]);
new PahoDemo().TestPahoClientPub();
}
public void setDetails(String topic,String message,String ipAddressEntered){
PahoDemo.topic=topic;
PahoDemo.clientMessage=message;
PahoDemo.ipAddress="tcp://"+ipAddressEntered+":1883";
}
public void TestPahoClientPub() throws IOException{
System.out.println("test pub ");
try {
MqttClient client = new MqttClient(ipAddress, "publisher");
client.connect();
MqttMessage message = new MqttMessage();
compressedMessage = PahoDemo.compress(clientMessage);
clientMessage = compressedMessage.toString();
message.setPayload(clientMessage.getBytes(Charset.forName("UTF-8")));
client.publish(topic, message);
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
public void doDemo() {
System.out.println("test sub");
try {
client = new MqttClient(ipAddress, "Subscriber");
client.connect();
client.setCallback(this);
client.subscribe(topic);
} catch (MqttException e) {
e.printStackTrace();
}
}
并将其添加到代码的顶部:package com;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
class SimpleCallback implements MqttCallback {
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static String decompress(final byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
byte[] bytes = IOUtils.toByteArray(gis);
return new String(bytes, "UTF-8");
}
public static String decompressArrived(MqttMessage message) throws IOException{
byte[] messagePayload = message.getPayload();
String messageDecompressed = decompress(messagePayload).toString();
return messageDecompressed;
}
@Override
public void connectionLost(Throwable cause) { //Called when the client lost the connection to the broker
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("-------------------------------------------------");
System.out.println("| Topic:" + topic);
System.out.println("| Message: " + new String(SimpleCallback.decompressArrived(message))); // here is the problem where the code stops
System.out.println("-------------------------------------------------");
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {//Called when a outgoing publish is complete
System.out.println("delivery complete");
}
}
public class MqttPublishSubscribeSample {
public static void main(String[] args){
String topic = args[0]; // topic name
String content = "Message from MqttPublishSample"; //payload of message
int qos = 2;
String broker = "tcp://"+args[1]+":1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: " + broker);
sampleClient.connect(connOpts);
sampleClient.subscribe("#", 1);
System.out.println("Connected");
System.out.println("Publish message: " + content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.setCallback(new SimpleCallback());
sampleClient.publish(topic, message); // just a test packet
System.out.println("Message published");
try {
Thread.sleep(5000);
} catch(Exception e) {
e.printStackTrace();
}
} catch(MqttException me){
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("cause " + me.getCause());
System.out.println("except " + me);
me.printStackTrace();
}
}
}
然后尝试从浏览器下载一些东西,它应该可以工作!
答案 1 :(得分:10)
2天后,我终于做到了。 对于有相同问题的人来说,这是一个简单的解决方案。 如果您正在使用MinimalExample,则必须下载Cefsharp示例(cefsharp-master)解压缩并执行此操作:
进入您的BrowserForm.cs类并输入:
browser.DownloadHandler = new DownloadHandler();
完成!
答案 2 :(得分:8)
I'm including the following because the implementation of OnBeforeDownloadFired() isn't shown in many online examples of how to use the DownloadHandler class, and it's missing from the DownloadHandler.cs cited.
This helped solve a nagging issue with downloading files (eg .mobi ebook) if the download link had the target "_blank". If there was no target, a download dialog was triggered. With a _blank target, I had to suppress a popup window and open a new custom tab in my browser, but when this happened, a download dialog was not triggered.
I think this is right. Hope it helps, or at least gives you a start:
DownloadHandler downer = new DownloadHandler(this);
browser.DownloadHandler = downer;
downer.OnBeforeDownloadFired += OnBeforeDownloadFired;
downer.OnDownloadUpdatedFired += OnDownloadUpdatedFired;
private void OnBeforeDownloadFired(object sender, DownloadItem e)
{
this.UpdateDownloadAction("OnBeforeDownload", e);
}
private void OnDownloadUpdatedFired(object sender, DownloadItem e)
{
this.UpdateDownloadAction("OnDownloadUpdated", e);
}
private void UpdateDownloadAction(string downloadAction, DownloadItem downloadItem)
{
/*
this.Dispatcher.Invoke(() =>
{
var viewModel = (BrowserTabViewModel)this.DataContext;
viewModel.LastDownloadAction = downloadAction;
viewModel.DownloadItem = downloadItem;
});
*/
}
// ...
public class DownloadHandler : IDownloadHandler
{
public event EventHandler<DownloadItem> OnBeforeDownloadFired;
public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
MainForm mainForm;
public DownloadHandler(MainForm form)
{
mainForm = form;
}
public void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
{
var handler = OnBeforeDownloadFired;
if (handler != null)
{
handler(this, downloadItem);
}
if (!callback.IsDisposed)
{
using (callback)
{
callback.Continue(downloadItem.SuggestedFileName, showDialog: true);
}
}
}
public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{
var handler = OnDownloadUpdatedFired;
if (handler != null)
{
handler(this, downloadItem);
}
}
}
// ...
答案 3 :(得分:0)
将此添加到您的主窗体中
CefBrowser = new ChromiumWebBrowser("http://google.com", null);
CefBrowser.Margin = Padding.Empty;
// browsers.Size = new Size(900, 600);// note here
DownloadHandler downloadHandler = new DownloadHandler();
CefBrowser.DownloadHandler = downloadHandler;
只需创建类 DownloadHandler
public class DownloadHandler : IDownloadHandler
{
public event EventHandler<DownloadItem> OnBeforeDownloadFired;
public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
public void OnBeforeDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem,
IBeforeDownloadCallback callback)
{
OnBeforeDownloadFired?.Invoke(this, downloadItem);
if (!callback.IsDisposed)
{
using (callback)
{
callback.Continue(downloadItem.SuggestedFileName, showDialog: true);
}
}
}
public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem,
IDownloadItemCallback callback)
{
OnDownloadUpdatedFired?.Invoke(this, downloadItem);
}
}