2016年6月23日 星期四

上傳 (DWR 五)

※pom.xml

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>

※上傳功能要用到這個jar,也可以到官方提供的demo檔copy

※如果沒給jar還是可以起,但要用到時,會報「java.lang.UnsupportedOperationException: File uploads not supported」錯誤



※.java

@Override
public String dealWith(FileTransfer ft) {
    if (ft.getSize() != 0) {
        System.out.println("filename=" + ft.getFilename());
        System.out.println("mimeType=" + ft.getMimeType());

        WebContext ctx = WebContextFactory.get();
        System.out.println("contextPath=" + ctx.getContextPath());
        System.out.println("realPath=" + ctx.getServletContext().getRealPath("/"));
        try {
            ft.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success!";
    }
    return "fail!";
}

※可以利用getMimeType()控制上傳的型態

※WebContext可以取得ContextPath和ServletContext



※.jsp

function fileUpload(){
    dao.dealWith(dwr.util.getValue('f'), {
        callback : function(rtn){
            dwr.util.setValue('sp', rtn);
        }
    });
}
----------
<input type="file" id="f" />
<input type="button" id="b" value="click me" onclick="fileUpload()" />
<span id="sp"></span>



※有進度條的上傳

要用到上一篇的activeReverseAjaxEnabled為true,所以web.xml要設定



※.java

public String dealWith(FileTransfer ft) {
    long size = ft.getSize();
    if (size != 0) {
        // 原始檔名
        String oFileName = ft.getFilename();
    
        // 隨機亂數 + 原始檔名
        String fileName = UUID.randomUUID() + "-" + oFileName.substring(oFileName.lastIndexOf("\\") + 1);
    
        // 檔案路徑
        String filePath = WebContextFactory.get().getServletContext().getRealPath("/") + "upload_file"
                + File.separator + fileName;
    
        // 建立檔案類別,順便產生必要的路徑
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    
        Browser.withCurrentPage(new Runnable() {
            @Override
            public void run() {
                try (
                    InputStream input = ft.getInputStream();
                    OutputStream output = new FileOutputStream(file)
                ) {
                    byte bArray[] = new byte[1024];
                    int len = 0;
                    // 目前長度
                    int currentLen = 0;
                    while ((len = input.read(bArray)) != -1) {
                        // 為了方便看進度條有在動,所以用sleep
                        Thread.sleep(50);
    
                        output.write(bArray, 0, len);
                        currentLen += len;
                        // 百分比
                        double precent = Math.ceil(currentLen / (double) size * 100);
                        ScriptSessions.addFunctionCall("xxx", size, currentLen, precent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return "success!";
    }
    return "fail!";
}

※addFunctionCall的xxx要對應到前端的function



※.jsp

dwr.engine.setActiveReverseAjax(true) ;
dwr.engine.setNotifyServerOnPageUnload(true) ;
    
function fileUpload(){
    dao.dealWith(dwr.util.getValue('f'), {
        callback : function(rtn){
            dwr.util.setValue('sp', rtn);
        }
    });
}
    
function xxx(size , currlen , percent) {
    document.getElementById("bar").style.width = percent + "%";
    document.getElementById("bar").innerHTML = percent + "%";
    
    // HTML5
    // document.getElementById("progress").value = percent;
    // document.getElementById("person").innerHTML = percent + "%";
    
    document.getElementById("allLeng").innerHTML = currlen + " | " + size;
}
----------
<input type="file" id="f" />
<input type="button" id="b" value="click me" onclick="fileUpload()" />
<span id="sp"></span>
    
<div style="width: 352px; border: 1px solid black; height: 30px;">
    <i id="bar" style="background: pink; float: left; height: 100%;"></i>
</div>
    
<!--     HTML5 -->
<!--     <div> -->
<!--         <progress max="100" value="0" id="progress"></progress> -->
<!--         <i id="person"></i> -->
<!--     </div> -->
<span id="allLeng"></span>

※註解的部分為HTML5才有的進度條標籤

沒有留言:

張貼留言