📄 dndapplet.java
字号:
/*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package dndapplet.applet;
import java.applet.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Container;
import java.awt.Color;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.net.*;
import java.util.zip.*;
/**
* This applet allows users to select files from their file system using drag
* and drop and upload them to a remote server. All files will be zipped and
* sent to the server as a single file to improve upload performance. This
* applet will use the HTTP protocol to communicate with the server.
*
*/
public class DNDApplet extends Applet implements DropTargetListener, ActionListener
{
/**
* This label shows the user the files they have selected and their status.
*/
private JLabel m_statusLabel;
/**
* This is the button which starts the upload process
*/
private JButton m_updload;
/**
* This button is a link to the display images page
*/
private JButton m_showImages;
/**
* This is the list of files which will be uploaded
*/
private ArrayList m_fileList = new ArrayList();
/**
* The init method creates all of the UI controls and performs all of the
* layout of the UI.
*/
public void init()
{
setLayout(new BorderLayout());
Container main = new Container();
add(main, BorderLayout.CENTER);
GridBagLayout gbl = new GridBagLayout();
main.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.6;
gbc.weightx = 0.00001;
gbc.gridy = 0;
gbc.gridx = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.insets = new Insets(1, 0, 1, 1);
/*
* This label will also serve as our drop target so we want to
* make sure it is big enough to be easy to drop files on to it.
*/
JLabel title = new JLabel("Drag and Drop Files Here");
title.setVerticalAlignment(SwingConstants.CENTER);
title.setHorizontalAlignment(SwingConstants.CENTER);
DropTarget dt2 = new DropTarget(title, this);
title.setBorder(new LineBorder(Color.black));
title.setOpaque(true);
main.add(title);
gbl.setConstraints(title, gbc);
/*
* The files to upload label and list
*/
JLabel files = new JLabel("Files to upload:");
gbc.gridy++;
gbc.insets = new Insets(25, 0, 1, 1);
gbc.weighty = 0.00001;
gbl.setConstraints(files, gbc);
main.add(files);
m_statusLabel = new JLabel();
gbc.gridy++;
gbc.insets = new Insets(1, 0, 1, 1);
gbc.weighty = 0.3;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
JScrollPane scroll = new JScrollPane(m_statusLabel);
main.add(scroll);
gbl.setConstraints(scroll, gbc);
/*
* The upload button
*/
m_updload = new JButton("Upload");
m_updload.addActionListener(this);
main.add(m_updload);
m_updload.setEnabled(false);
gbc.fill = GridBagConstraints.NONE;
gbc.gridy++;
gbl.setConstraints(m_updload, gbc);
/*
* The view button
*/
m_showImages = new JButton("View Images");
m_showImages.addActionListener(this);
main.add(m_showImages);
gbc.gridx = 1;
gbl.setConstraints(m_showImages, gbc);
}
/**
* This method handles actually uploading the selected files to the server.
*/
private void putData()
{
/*
* This method needs to gather up each of the files the user has selected,
* zip those files together, and send that zip file up to the server.
*/
HttpURLConnection conn = null;
try {
String url = getDocumentBase().toString();
url = url.substring(0, url.lastIndexOf("/"));
/*
* Create and setup our HTTP connection. This connection will use
* the PUT method, will not follow redirects, and will use the
* application/zip content type.
*/
conn = (HttpURLConnection) new URL(url + "/imageview.htm").openConnection();
conn.setRequestMethod("PUT");
conn.setFollowRedirects(false);
conn.setRequestProperty("content-type", "application/zip");
/*
* Most HTTP connections do not have any ouput. The most common case
* is to set up a number of parameters and then make a request to the
* server without any additional data. We want to send the file data
* up to the server so we need to explicitely tell the connection that
* we intend to send output to the server.
*/
conn.setDoOutput(true);
/*
* This zip output stream will server as our stream to the server and
* will zip each file while it sends it to the server.
*/
ZipOutputStream out = new ZipOutputStream(conn.getOutputStream());
for (int i = 0; i < m_fileList.size(); i++) {
/*
* For each file we will create a new entry in the ZIP archive and
* stream the file into that entry.
*/
File f = (File) m_fileList.get(i);
ZipEntry entry = new ZipEntry(f.getName());
out.putNextEntry(entry);
InputStream in = new FileInputStream(f);
int read;
byte[] buf = new byte[1024];
while ((read = in.read(buf)) > 0) {
out.write(buf, 0, read);
}
out.closeEntry();
}
/*
* Once we are done writing out our stream we will finish building the
* archive and close the stream.
*/
out.finish();
out.close();
/*
* Now that we have set all the connection parameters and prepared all
* the data we are ready to connect to the server.
*/
conn.connect();
try {
/*
* If we got a 401 (unauthorized), we can't get that data. We will
* get an IOException. This makes no sense since a 401 does not
* consitute an IOException, it just says we need to provide the
* username again.
*/
System.out.println("conn.getResponseCode(): " + conn.getResponseCode());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
System.out.println("conn.getResponseCode(): " + conn.getResponseCode());
System.out.println("conn.getResponseMessage(): " + conn.getResponseMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
/*
* Once we are done we want to make sure to disconnect from the server.
*/
if (conn != null)
conn.disconnect();
}
/*
* Now that the upload is complete we can let the user know that it was a success.
*/
m_statusLabel.setText("Upload complete");
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == m_updload) {
putData();
} else if (e.getSource() == m_showImages) {
String url = getDocumentBase().toString();
url = url.substring(0, url.lastIndexOf("/"));
try {
getAppletContext().showDocument(new URL(url + "/imageview.htm"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void dragExit(DropTargetEvent dte)
{
// System.out.println("dragExit(" + dte + ")");
}
public void dragEnter(DropTargetDragEvent dtde)
{
// System.out.println("dragenter(" + dtde + ")");
}
public void dragOver(DropTargetDragEvent dtde)
{
// System.out.println("dragOver(" + dtde + ")");
}
public void dropActionChanged(DropTargetDragEvent dtde)
{
// System.out.println("dropActionChanged(" + dtde + ")");
}
/**
* This method will be called when the user drops a file on our target label.
*
* @param dtde
*/
public void drop(DropTargetDropEvent dtde)
{
int action = dtde.getDropAction();
/*
* We have to tell Java that we are going to accept this drop before
* we try to access any of the data.
*/
dtde.acceptDrop(action);
fromTransferable(dtde.getTransferable());
/*
* Once the drop event is complete we need to notify Java again so it
* can reset the cursor and finish showing the drop behavior.
*/
dtde.dropComplete(true);
}
/**
* This is a helper method to get the data from the drop event.
*
* @param t
*/
private void fromTransferable(Transferable t)
{
if (t == null)
return;
/*
* The user may have dropped a file or anything else from any application
* running on their computer. This interaction is handled with data flavors.
* For example, text copied from OpenOffice might have one flavor which
* contains the text with formatting information and another flavor which
* contains the text without any of this information. We need to look for
* the data flavor we know how to support and read the list of files from it.
*/
try {
DataFlavor flavors[] = t.getTransferDataFlavors();
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
/*
* We are looking for the list of files data flavor. This will be a
* list of the paths to the files the user dragged and dropped on to
* our application.
*/
List list = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
m_fileList.addAll(list);
/*
* We are going to take the path to each file and add it to the list
* so the user can see which files they have selected.
*/
StringBuffer sb = new StringBuffer();
sb.append("<HTML><UL>");
for (int i = 0; i < m_fileList.size(); i++) {
File f = (File) m_fileList.get(i);
sb.append("<LI>" + f + "</LI>\n");
}
sb.append("</UL></HTML>");
m_statusLabel.setText(sb.toString());
/*
* Now that we have at least one file to upload we can enable the
* upload button.
*/
m_updload.setEnabled(true);
} else {
/*
* There is a very large number of other data flavors the user can
* drop onto our applet. we will just show the information from
* those types, but we can't get a list of files to upload from
* them.
*/
DataFlavor df = DataFlavor.selectBestTextFlavor(flavors);
JOptionPane.showMessageDialog(this, "df: " + df);
JOptionPane.showMessageDialog(this, "t.getTransferData(df): " + t.getTransferData(df));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -