国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Structs下上傳文件進度顯示

Charlie_Jade / 932人閱讀

摘要:兩種思路,一種是使用插件,使用插件就比較簡單,進度在前端實現,記錄發送的文件大小并提供函數。另一種就是在后臺監聽接收數據,前臺使用輪回實時讀取展示進度信息。環境前臺上傳插件,后臺。

兩種思路,一種是使用plupload插件,使用插件就比較簡單,進度在前端實現,plupload記錄發送的文件大小并提供函數。具體可參考http://www.plupload.com/官網。

另一種就是在后臺監聽接收數據,前臺使用ajax輪回實時讀取展示進度信息。

本文旨在敘述第二種方法后臺方法。

環境:前臺上傳插件http://www.jq22.com/jquery-in...,后臺Structs。(注插件提供了springmvc版本的進度顯示)

1、定義返回信息實體類

public class UploadStatus {
    private long bytesRead;//已讀數據
    private long contentLength;//文件總數據
    private long items;//第幾個文件
    private long startTime = System.currentTimeMillis();//開始時間
    private long useTime = System.currentTimeMillis();//已用時間
    private int percent;//完成百分比
    
    public long getBytesRead() {
        return bytesRead;
    }
    public void setBytesRead(long bytesRead) {
        this.bytesRead = bytesRead;
    }
    public long getContentLength() {
        return contentLength;
    }
    public void setContentLength(long contentLength) {
        this.contentLength = contentLength;
    }
    public long getItems() {
        return items;
    }
    public void setItems(long items) {
        this.items = items;
    }
    public long getStartTime() {
        return startTime;
    }
    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }
    public long getUseTime() {
        return useTime;
    }
    public void setUseTime(long useTime) {
        this.useTime = useTime;
    }
    public int getPercent() {
        return percent;
    }
    public void setPercent(int percent) {
        this.percent = percent;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "UploadStatus [percent=" + percent + ", items=" + items + "]";
    }
}

2、創建監聽類實現ProgressListener

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;

public class UploadListener implements ProgressListener{
    private HttpSession session;
    public UploadListener(HttpSession session){
        super();
        this.session = session;
        UploadStatus uploadStatus = new UploadStatus();
        session.setAttribute("upload_status", uploadStatus);
    }
    
    @Override
    public void update(long bytesRead, long contentLength, int items) {
        // TODO Auto-generated method stub
        UploadStatus uploadStatus = (UploadStatus) session.getAttribute("upload_status");
        uploadStatus.setBytesRead(bytesRead);
        uploadStatus.setContentLength(contentLength);
        uploadStatus.setItems(items);
        uploadStatus.setUseTime(System.currentTimeMillis()-uploadStatus.getStartTime());
        uploadStatus.setPercent((int)(100*bytesRead/contentLength));
        session.setAttribute("upload_status", uploadStatus);
        
    }
    
}

3、實現MultiPartRequest接口,主要是讓自己的監聽事件監聽上傳

package com.cngrain.util;

import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.StrutsConstants;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.dispatcher.multipart.MultiPartRequest;

public class UploadCommonsMultipartResolver implements MultiPartRequest {
    static final Logger LOG = LoggerFactory.getLogger(MultiPartRequest.class);

    // maps parameter name -> List of FileItem objects
    protected Map> files = new HashMap>();

    // maps parameter name -> List of param values
    protected Map> params = new HashMap>();

    // any errors while processing this request
    protected List errors = new ArrayList();

    protected long maxSize;

    @Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE)
    public void setMaxSize(String maxSize) {
        this.maxSize = Long.parseLong(maxSize);
    }

    /**
     * Creates a new request wrapper to handle multi-part data using methods
     * adapted from Jason Pell"s multipart classes (see class description).
     * 
     * @param saveDir
     *            the directory to save off the file
     * @param request
     *            the request containing the multipart
     * @throws java.io.IOException
     *             is thrown if encoding fails.
     */
    public void parse(HttpServletRequest request, String saveDir) throws IOException {
        try {
            processUpload(request, saveDir);
        } catch (FileUploadException e) {
            LOG.warn("Unable to parse request", e);
            errors.add(e.getMessage());
        }
    }

    private void processUpload(HttpServletRequest request, String saveDir)
            throws FileUploadException, UnsupportedEncodingException {
        for (FileItem item : parseRequest(request, saveDir)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found item " + item.getFieldName());
            }
            if (item.isFormField()) {
                processNormalFormField(item, request.getCharacterEncoding());
            } else {
                processFileField(item);
            }
        }
    }

    private void processFileField(FileItem item) {
        LOG.debug("Item is a file upload");

        // Skip file uploads that don"t have a file name - meaning that no file
        // was selected.
        if (item.getName() == null || item.getName().trim().length() < 1) {
            LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
            return;
        }

        List values;
        if (files.get(item.getFieldName()) != null) {
            values = files.get(item.getFieldName());
        } else {
            values = new ArrayList();
        }

        values.add(item);
        files.put(item.getFieldName(), values);
    }

    private void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException {
        LOG.debug("Item is a normal form field");
        List values;
        if (params.get(item.getFieldName()) != null) {
            values = params.get(item.getFieldName());
        } else {
            values = new ArrayList();
        }

        // note: see http://jira.opensymphony.com/browse/WW-633
        // basically, in some cases the charset may be null, so
        // we"re just going to try to "other" method (no idea if this
        // will work)
        if (charset != null) {
            values.add(item.getString(charset));
        } else {
            values.add(item.getString());
        }
        params.put(item.getFieldName(), values);
    }

    private List parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException {
        DiskFileItemFactory fac = createDiskFileItemFactory(saveDir);
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        /* 自己新建監聽器 */
        UploadListener progressListener = new UploadListener(servletRequest.getSession());
        upload.setProgressListener(progressListener);// 添加自己的監聽器

        return upload.parseRequest(createRequestContext(servletRequest));
    }

    private DiskFileItemFactory createDiskFileItemFactory(String saveDir) {
        DiskFileItemFactory fac = new DiskFileItemFactory();
        // Make sure that the data is written to file
        fac.setSizeThreshold(0);
        if (saveDir != null) {
            fac.setRepository(new File(saveDir));
        }
        return fac;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#
     * getFileParameterNames()
     */
    public Enumeration getFileParameterNames() {
        return Collections.enumeration(files.keySet());
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.struts2.dispatcher.multipart.MultiPartRequest#getContentType(
     * java.lang.String)
     */
    public String[] getContentType(String fieldName) {
        List items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List contentTypes = new ArrayList(items.size());
        for (FileItem fileItem : items) {
            contentTypes.add(fileItem.getContentType());
        }

        return contentTypes.toArray(new String[contentTypes.size()]);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFile(java.
     * lang.String)
     */
    public File[] getFile(String fieldName) {
        List items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List fileList = new ArrayList(items.size());
        for (FileItem fileItem : items) {
            File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
            if (fileItem.isInMemory() && storeLocation != null && !storeLocation.exists()) {
                try {
                    storeLocation.createNewFile();
                } catch (IOException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Cannot write uploaded empty file to disk: " + storeLocation.getAbsolutePath(), e);
                    }
                }
            }
            fileList.add(storeLocation);
        }

        return fileList.toArray(new File[fileList.size()]);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileNames(
     * java.lang.String)
     */
    public String[] getFileNames(String fieldName) {
        List items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List fileNames = new ArrayList(items.size());
        for (FileItem fileItem : items) {
            fileNames.add(getCanonicalName(fileItem.getName()));
        }

        return fileNames.toArray(new String[fileNames.size()]);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#
     * getFilesystemName(java.lang.String)
     */
    public String[] getFilesystemName(String fieldName) {
        List items = files.get(fieldName);

        if (items == null) {
            return null;
        }

        List fileNames = new ArrayList(items.size());
        for (FileItem fileItem : items) {
            fileNames.add(((DiskFileItem) fileItem).getStoreLocation().getName());
        }

        return fileNames.toArray(new String[fileNames.size()]);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameter(
     * java.lang.String)
     */
    public String getParameter(String name) {
        List v = params.get(name);
        if (v != null && v.size() > 0) {
            return v.get(0);
        }

        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#
     * getParameterNames()
     */
    public Enumeration getParameterNames() {
        return Collections.enumeration(params.keySet());
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#
     * getParameterValues(java.lang.String)
     */
    public String[] getParameterValues(String name) {
        List v = params.get(name);
        if (v != null && v.size() > 0) {
            return v.toArray(new String[v.size()]);
        }

        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getErrors()
     */
    public List getErrors() {
        return errors;
    }

    /**
     * Returns the canonical name of the given file.
     * 
     * @param filename
     *            the given file
     * @return the canonical name of the given file
     */
    private String getCanonicalName(String filename) {
        int forwardSlash = filename.lastIndexOf("/");
        int backwardSlash = filename.lastIndexOf("");
        if (forwardSlash != -1 && forwardSlash > backwardSlash) {
            filename = filename.substring(forwardSlash + 1, filename.length());
        } else if (backwardSlash != -1 && backwardSlash >= forwardSlash) {
            filename = filename.substring(backwardSlash + 1, filename.length());
        }

        return filename;
    }

    /**
     * Creates a RequestContext needed by Jakarta Commons Upload.
     * 
     * @param req
     *            the request.
     * @return a new request context.
     */
    private RequestContext createRequestContext(final HttpServletRequest req) {
        return new RequestContext() {
            public String getCharacterEncoding() {
                return req.getCharacterEncoding();
            }

            public String getContentType() {
                return req.getContentType();
            }

            public int getContentLength() {
                return req.getContentLength();
            }

            public InputStream getInputStream() throws IOException {
                InputStream in = req.getInputStream();
                if (in == null) {
                    throw new IOException("Missing content in the request");
                }
                return req.getInputStream();
            }
        };
    }

    @Override
    public void cleanUp() {
        // TODO Auto-generated method stub

    }

}

4、.配置struts.xml





5、編寫action獲取上傳信息

    @Action(value = "getStatus", results = { @Result(name = SUCCESS,  type = "json" ) }) 
    public String getStatus(){
        uploadStatus = (UploadStatus)request.getSession().getAttribute("upload_status");
        return SUCCESS;
    }

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/67809.html

相關文章

  • 【許曉笛】 EOS 智能合約案例解析(3)

    摘要:文件地址智能合約文件由部分組成定義類型的別名各個類型的數據結構智能合約的數據結構體李嘉圖條款注格式不支持注釋,上面的雙斜線大家理解就好。是李嘉圖合約,剛剛被加入到智能合約中,官方還沒有進一步說明。 詳解 EOS 智能合約的 abi 文件 這次向大家介紹 eosio.token 智能合約的最后一個文件 —— abi文件。ABI 全稱 Application Binary Interfac...

    philadelphia 評論0 收藏0
  • H5拖放異步文件上傳之二——上傳進度監聽

    摘要:添加功能顯示待上傳文件列表支持移除待上傳文件使用顯示上傳進度支持中斷上傳方法返回一個對象,用來表示上傳的進度。監聽數據傳輸進行中通過監聽這個事件,可獲得上傳進度。 ??上一篇《H5拖放+FormData接口+NodeJS,完整異步文件上傳(一)》,我們走通了拖放文件上傳的整個流程,但離實際使用場景還有差距。這篇,我們來添加幾個實際使用場景必要的功能,向實際使用再走一步。 添加功能 顯...

    Godtoy 評論0 收藏0
  • H5拖放異步文件上傳之二——上傳進度監聽

    摘要:添加功能顯示待上傳文件列表支持移除待上傳文件使用顯示上傳進度支持中斷上傳方法返回一個對象,用來表示上傳的進度。監聽數據傳輸進行中通過監聽這個事件,可獲得上傳進度。 ??上一篇《H5拖放+FormData接口+NodeJS,完整異步文件上傳(一)》,我們走通了拖放文件上傳的整個流程,但離實際使用場景還有差距。這篇,我們來添加幾個實際使用場景必要的功能,向實際使用再走一步。 添加功能 顯...

    blankyao 評論0 收藏0
  • TP5整合阿里云OSS上傳文件第二節,異步上傳頭像實現,

    摘要:版本也是我最喜歡的方式這個代碼有點黏在一起了湊合看把李昊天創建實例服務器異步接受地址指定選擇文件的按鈕容器禁止多選不壓縮選擇之后自動上傳防止低版本瀏覽器用到了只允許選擇圖片文件。 TP5整合阿里云OSS上傳文件第二節,上傳頭像實現首先先看一個效果圖上傳失敗效果圖:showImg(https://segmentfault.com/img/bVbaJLZ?w=983&h=561);上傳成功...

    douzifly 評論0 收藏0

發表評論

0條評論

Charlie_Jade

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<