⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileuploadapplet.java

📁 一个cms内容管理平台
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                m_fileSelector.setDialogTitle(m_actionOutputSelect);

                // add two custom file filters (office and images) and the default filters
                m_fileSelector.addChoosableFileFilter(new ImageFilter());
                m_fileSelector.addChoosableFileFilter(new OfficeFilter());
                m_fileSelector.setAcceptAllFileFilterUsed(true);
                // enable multi-selection of files
                m_fileSelector.setMultiSelectionEnabled(true);
                // add custom icons for file types.
                m_fileSelector.setFileView(new ImageFileView(m_opencms, m_fileExtensions));
                // add the image preview pane.
                m_fileSelector.setAccessory(new ImagePreview(m_fileSelector, m_messageNoPreview));

                m_action = m_actionOutputSelect;
                repaint();

                // show the file selector dialog
                int returnVal = m_fileSelector.showDialog(this, "OK");

                // process the results.
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    // count all resources
                    m_outputMode = 1;
                    m_action = m_actionOutputCount;
                    repaint();
                    m_resources = countResources(m_fileSelector.getSelectedFiles());
                    // create the zipfile  
                    m_outputMode = 2;
                    File targetFile = createZipFile(m_fileSelector.getSelectedFiles());
                    // check the size of the zip files
                    if ((targetFile == null) || ((m_maxsize > 0) && (targetFile.length() > m_maxsize))) {
                        // show some details in the applet itself
                        m_outputMode = 4;
                        if (targetFile == null) {
                            m_message = m_messageOutputErrorZip;
                        } else {
                            m_message = m_messageOutputErrorSize + " " + targetFile.length() + " > " + m_maxsize;
                        }
                        m_action = m_actionOutputError;
                        repaint();
                        // show an error-alertbog
                        JOptionPane.showMessageDialog(this, m_message, m_action, JOptionPane.ERROR_MESSAGE);
                    } else {
                        m_outputMode = 3;
                        m_message = m_messageOutputUpload + " (" + targetFile.length() / 1024 + " kb)";
                        repaint();
                        // upload the zipfile
                        FileUploadThread uploadThreat = new FileUploadThread();

                        uploadThreat.init(this);
                        uploadThreat.start();

                        uploadZipFile(targetFile);
                        ok = false;
                    }

                } else {
                    //the cancel button was used, so go back to the workplace
                    ok = false;
                    getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
                }
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @see java.applet.Applet#start()
     */
    public void start() {

        if (m_certificateAccepted) {
            // certificate was accepted, start upload thread
            m_runner = new Thread(this);
            m_runner.start();
        } else {
            // certificate was not accepted, show error message
            displayError();
        }
    }

    /**
     * @see java.applet.Applet#stop()
     */
    public void stop() {

        m_runner = null;
    }

    /**
     * @see java.awt.Component#update(java.awt.Graphics)
     */
    public void update(Graphics g) {

        paint(g);
    }

    /**
     * Adds a single file to the zip output.<p>
     * 
     * @param zipStream the zip output stream
     * @param file the file to add to the stream
     * @param filename the name of the file to add
     * @throws Exception if something goes wrong
     */
    private void addFileToZip(ZipOutputStream zipStream, File file, String filename) throws Exception {

        // add to zipfile
        String name = filename;
        if (name.length() > 40) {
            name = "..." + name.substring(name.length() - 40, name.length());
        }
        m_message = m_messageOutputAdding + " " + name + "..";
        m_step++;
        repaint();
        ZipEntry entry = new ZipEntry(filename);
        zipStream.putNextEntry(entry);
        zipStream.write(getFileBytes(file));
        zipStream.closeEntry();
    }

    /**
     * Adds a folder and all subresources to the zip output.<p>
     * 
     * @param zipStream the zip output stream
     * @param file the file to add to the stream
     * @param prefix the foldername prefix
     * @throws Exception if something goes wrong
     */
    private void addFolderToZip(ZipOutputStream zipStream, File file, String prefix) throws Exception {

        String foldername = file.getName();

        prefix += "/" + foldername;
        // get all subresources
        File[] subresources = file.listFiles();
        // loop through the results                        
        for (int i = 0; i < subresources.length; i++) {
            // add it its a file
            if (subresources[i].isFile()) {

                // use the prefix for the filename, since it inside the folder     
                addFileToZip(zipStream, subresources[i], prefix + "/" + subresources[i].getName());
            } else {
                // recurse into the subfolder
                addFolderToZip(zipStream, subresources[i], prefix);
            }
        }
    }

    /**
     * Counts all resources to add to the zip file.<p>
     * 
     * @param files the files to be packed into the zipfile
     * @return number of resources
     */
    private int countResources(File[] files) {

        int count = 0;
        // look through all selected resources
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                // its a file, count it
                count++;
            } else {
                // its a folder, count all resources in it and add the number
                count += countSubresources(files[i]);
            }
        }
        return count;
    }

    /**
     * Counts all resources in a folder.<p>
     * 
     * @param folder the folder to count
     * @return number of resources
     */
    private int countSubresources(File folder) {

        int count = 0;
        if (folder.isFile()) {
            // check if is really a folder
            count = 1;
        } else {
            // recurest to count
            count = countResources(folder.listFiles());
        }
        return count;
    }

    /**
     * Creates a ZipFile from all files to upload.<p>
     * 
     * @param files the files to be packed into the zipfile
     * @return reference to the zipfile
     */
    private File createZipFile(File[] files) {

        File targetFile = null;
        m_action = m_actionOutputCreate;
        try {
            // create a new zipStream
            String zipFileName = ".opencms_upload.zip";
            String userHome = System.getProperty("user.home");
            // create file in user home directory where write permissions should exist
            if (userHome != null) {
                if (!userHome.endsWith(File.separator)) {
                    userHome = userHome + File.separator;
                }
                zipFileName = userHome + zipFileName;
            }
            ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            // loop through all files
            for (int i = 0; i < files.length; i++) {

                // if its a file, add it to the zipfile
                if (files[i].isFile()) {
                    addFileToZip(zipStream, files[i], files[i].getName());
                } else {
                    addFolderToZip(zipStream, files[i], "");
                }
                repaint();
                // free mem
                files[i] = null;
            }
            zipStream.close();
            // get the zipfile
            targetFile = new File(zipFileName);
        } catch (Exception e) {
            System.err.println("Error creating zipfile " + e);
        }
        return targetFile;

    }

    /**
     * Extracts the colors from the parameter String.<p>
     * 
     * @param colors list of color names and values
     * @return HashMap with color names and values
     */
    private HashMap extractColors(String colors) {

        HashMap colorStorage = new HashMap();

        if (colors != null) {
            StringTokenizer tok = new StringTokenizer(colors, ",");
            // loop through the tokens
            // all tokens have the format "extension=type"    
            while (tok.hasMoreElements()) {
                String token = tok.nextToken();
                // now extract the file extension and the type
                String colorName = token.substring(0, token.indexOf("="));
                String colorValue = token.substring(token.indexOf("=") + 1);
                colorStorage.put(colorName, colorValue);
            }
        }
        return colorStorage;
    }

    /**
     * Gets a color for drawing the output.<p>
     * 
     * @param colorName the name of the color
     * @return color
     */
    private Color getColor(String colorName) {

        Color col = Color.black;
        try {
            col = Color.decode((String)m_colors.get(colorName));
        } catch (Exception e) {
            System.err.println("Error reading " + colorName + ":" + e);
        }
        return col;
    }

    /**
     * Returns a byte array containing the content of server FS file.<p>
     *
     * @param file the name of the file to read
     * @return bytes[] the content of the file
     * @throws Exception if something goes wrong
     */
    private byte[] getFileBytes(File file) throws Exception {

        byte[] buffer = null;
        FileInputStream fileStream = null;
        int charsRead;
        int size;
        try {
            fileStream = new FileInputStream(file);
            charsRead = 0;
            size = new Long(file.length()).intValue();
            buffer = new byte[size];
            while (charsRead < size) {
                charsRead += fileStream.read(buffer, charsRead, size - charsRead);
            }
            return buffer;
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (fileStream != null) {
                    fileStream.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    /**
     * Uploads the zipfile to the OpenCms.<p>
     * 
     * @param uploadFile the zipfile to upload
     */
    private void uploadZipFile(File uploadFile) {

        m_action = m_actionOutputUpload;
        repaint();

        PostMethod post = new PostMethod(m_targetUrl);

        try {
            Part[] parts = new Part[4];
            parts[0] = new FilePart(uploadFile.getName(), uploadFile);
            parts[1] = new StringPart("action", "submitform");
            parts[2] = new StringPart("unzipfile", "true");
            parts[3] = new StringPart("uploadfolder", m_uploadFolder);

            HttpMethodParams methodParams = post.getParams();
            methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
            post.setRequestEntity(request);

            // add jsessionid query string
            String sessionId = getParameter("sessionId");
            String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
            post.setQueryString(query);
            post.addRequestHeader(C_JSESSIONID, sessionId);

            HttpClient client = new HttpClient();
            HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
            connectionParams.setConnectionTimeout(5000);

            // add the session cookie
            client.getState();
            client.getHostConfiguration().getHost();

            HttpState initialState = new HttpState();
            URI uri = new URI(m_targetUrl, false);
            Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
            initialState.addCookie(sessionCookie);
            client.setState(initialState);

            // no execute the file upload
            int status = client.executeMethod(post);

            if (status == HttpStatus.SC_OK) {
                //return to the specified url and frame target
                getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
            } else {
                // create the error text
                String error = m_errorLine1 + "\n" + post.getStatusLine();
                //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
                getAppletContext().showDocument(
                    new URL(m_errorUrl + "?action=showerror&uploaderror=" + error),
                    "explorer_files");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
            // finally delete the zipFile on the harddisc
            uploadFile.delete();
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -