com.zlfun.framework.misc.UploadUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.zlfun.framework.misc.UploadUtils.java

Source

package com.zlfun.framework.misc;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Brin
 */
public class UploadUtils {

    public static byte[] getFileBytes(HttpServletRequest request) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // ???
        // ??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // ??

        //  ?? 
        factory.setSizeThreshold(1024 * 1024);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            // ?
            List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

            for (FileItem item : list) {
                // ????
                String name = item.getFieldName();

                // ? ??  ?
                if (item.isFormField()) {
                    // ? ?????? 
                    String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

                    request.setAttribute(name, value);
                } // ? ??  
                else {
                    /**
                     * ?? ??
                     */
                    // ???
                    String value = item.getName();
                    // ?
                    // ????
                    value = java.net.URLDecoder.decode(value, "UTF-8");
                    int start = value.lastIndexOf("\\");
                    // ?  ??1 ???
                    String filename = value.substring(start + 1);

                    InputStream in = item.getInputStream();
                    int length = 0;
                    byte[] buf = new byte[1024];
                    System.out.println("??" + item.getSize());
                    // in.read(buf) ?? buf 
                    while ((length = in.read(buf)) != -1) {
                        //  buf  ??  ??
                        out.write(buf, 0, length);
                    }

                    try {

                        if (in != null) {
                            in.close();
                        }

                    } catch (IOException ex) {
                        Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    return out.toByteArray();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
            }
        }
        return null;

    }

    private static String getBrowser(HttpServletRequest request) {
        String agent = request.getHeader("USER-AGENT");
        if (agent == null) {
            return null;
        }
        String userAgent = agent.toLowerCase();

        if (userAgent.indexOf("msie") >= 0) {

            return "IE";

        } else if (userAgent.indexOf("mozilla") >= 0) {

            return "FF";

        } else if (userAgent.indexOf("applewebkit") >= 0) {

            return "CH";

        } else if (userAgent.indexOf("safari") >= 0) {

            return "SF";

        } else if (userAgent.indexOf("opera") >= 0) {

            return "OP";

        }

        return null;

    }

    public static String getContentDisposition(HttpServletRequest request, String fileName) {
        String contentDisposition = "";
        String browser = getBrowser(request);
        try {
            if ("IE".equals(browser)) {
                contentDisposition = "attachment; filename="
                        + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
            } else if ("CH".equals(browser)) {
                contentDisposition = "attachment; filename=" + MimeUtility.encodeText(fileName, "UTF8", "B");
            } else if ("SF".equals(browser)) {
                contentDisposition = "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            } else {
                contentDisposition = "attachment; filename*=UTF-8''"
                        + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return contentDisposition;

    }

    // ???
    public static boolean download(HttpServletRequest request, HttpServletResponse response, String uuid) {

        InputStream bis;
        boolean ret = false;
        try {

            byte[] voiceData = FsUtils.readFromDisk(uuid);
            if (voiceData != null) {
                long p = 0L;
                long toLength = 0L;
                long contentLength = 0L;
                int rangeSwitch = 0; // 0,1,?bytes=27000-2,???bytes=27000-39000
                long fileLength;
                String rangBytes = "";
                fileLength = voiceData.length;

                // get file content
                bis = new ByteArrayInputStream(voiceData);

                // tell the client to allow accept-ranges
                response.reset();
                response.setHeader("Accept-Ranges", "bytes");

                // client requests a file block download start byte
                String range = request.getHeader("Range");
                if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                    rangBytes = range.replaceAll("bytes=", "");
                    if (rangBytes.endsWith("-")) { // bytes=270000-
                        rangeSwitch = 1;
                        p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                        contentLength = fileLength - p; // 270000?bytes270000
                    } else { // bytes=270000-320000
                        rangeSwitch = 2;
                        String temp1 = rangBytes.substring(0, rangBytes.indexOf("-"));
                        String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length());
                        p = Long.parseLong(temp1);
                        toLength = Long.parseLong(temp2);
                        contentLength = toLength - p + 1; // 
                        // 270000-320000
                        // 
                    }
                } else {
                    contentLength = fileLength;
                }

                // Content-Length?????
                // Content-Length: [?] - [?]
                response.setHeader("Content-Length", new Long(contentLength).toString());

                // 
                // ??:
                // Content-Range: bytes [?]-[? - 1]/[?]
                if (rangeSwitch == 1) {
                    String contentRange = new StringBuffer("bytes ").append(new Long(p).toString()).append("-")
                            .append(new Long(fileLength - 1).toString()).append("/")
                            .append(new Long(fileLength).toString()).toString();
                    response.setHeader("Content-Range", contentRange);
                    bis.skip(p);
                } else if (rangeSwitch == 2) {
                    String contentRange = range.replace("=", " ") + "/" + new Long(fileLength).toString();
                    response.setHeader("Content-Range", contentRange);
                    bis.skip(p);
                } else {
                    String contentRange = new StringBuffer("bytes ").append("0-").append(fileLength - 1).append("/")
                            .append(fileLength).toString();
                    response.setHeader("Content-Range", contentRange);
                }

                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", getContentDisposition(request, uuid));

                OutputStream out = response.getOutputStream();

                int n = 0;
                long readLength = 0;
                int bsize = 1024;
                byte[] bytes = new byte[bsize];
                if (rangeSwitch == 2) {
                    //  bytes=27000-39000 27000?
                    while (readLength <= contentLength - bsize) {
                        n = bis.read(bytes);
                        readLength += n;
                        out.write(bytes, 0, n);
                    }
                    if (readLength <= contentLength) {
                        n = bis.read(bytes, 0, (int) (contentLength - readLength));
                        out.write(bytes, 0, n);
                    }
                } else {
                    while ((n = bis.read(bytes)) != -1) {
                        out.write(bytes, 0, n);
                    }
                }
                out.flush();
                out.close();
                bis.close();
                return true;
            } else {
                return false;
            }
        } catch (IOException ex) {
            //  ClientAbortException 
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (Exception ex) {
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

    }

}