我正在尝试从applet编写示例文件但是无法正常工作。以下是代码。
小程序
public class PasteImageApplet extends JApplet {
Clipboard clipboard;
Toolkit toolkit;
JLabel lbl;
public String getClipboardImageURL(String server) {
lbl.setText("pasting image");
String url = "";
try {
DataFlavor dataFlavor = DataFlavor.imageFlavor;
System.out.println(dataFlavor.getDefaultRepresentationClass());
Object object = null;
try {
object = clipboard.getContents(null)
.getTransferData(dataFlavor);
JOptionPane.showMessageDialog(null,"Image found.");
try
{
Writer output = null;
String text = "Test Write File";
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Error writing file"+ex);
return "" ;
}
//return "";
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "No image found.");
return "";
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error."+e);
return "";
}
return url;
}
public void init() {
lbl = new JLabel("");
lbl.setText("applet started");
add(lbl);
toolkit = Toolkit.getDefaultToolkit();
clipboard = toolkit.getSystemClipboard();
}
}
HTML
<html>
<head>
<title>Clipboard image demo</title>
<script type="text/javascript">
function loadApplet() {
// Deferred load to display text first
document.getElementById("applet").innerHTML = '<object id="paste-image" classid="java:PasteImageApplet.class" type="application/x-java-applet" archive="tst.jar" width="1" height="1"></object>';
}
function getImage() {
obj = document.getElementById('paste-image');
postTo = "http://localhost/PasteImageApplet/PasteImageApplet/Web/shoot.php"; // Change this to your URL
image = obj.getClipboardImageURL(postTo);
if (image) {
url = "shots/" + image;
document.getElementById("target").src = url;
document.getElementById("url").value = document.getElementById("target").src; // to get full path, hack, I know ;)
document.getElementById("container").style.display = "";
}
}
</script>
<body onload="loadApplet();">
<p>
Copy some image data to your clipboard, accept the applet (it only accesses the clipboard) and click the button :-)
<a href="http://lassebunk.dk/2009/07/19/using-the-clipboard-to-post-images/">See a blog post about this demo</a>
</p>
<p>
<div id="applet"></div>
<input type="button" value="Paste it!" onclick="getImage();">
</p>
<div id="container" style="display: none;">
<input type="text" id="url" style="width: 700px;"><br />
<iframe id="target" width="700" height="400"></iframe>
</div>
</body>
</html>
我也没有收到任何错误。请指教。
答案 0 :(得分:1)
那是因为applet存在自己的沙箱,在那里他们需要特殊的权限来执行某些操作,比如读取或写入客户机的磁盘。请记住,applet在客户端计算机的上下文中执行,他们是访客,需要遵守内部规则
答案 1 :(得分:1)
小程序无法在服务器上建立File
。这不是服务器的工作方式。如果服务器接受上传,它必须提供特定的功能来启用它,并且applet必须使用该功能。
只要接受上传的功能在同一台服务器上,applet就可以保持沙盒状态。
答案 2 :(得分:0)
你可以通过(windows)任务栏看到applet的控制台,你右键单击java图标(当applet运行时它应该出现在右下方)并右键单击&gt;打开控制台,你可以在那里调试,这是applet的堆栈跟踪的地方。