程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> jquery uploadify和apache Fileupload完成異步上傳文件示例

jquery uploadify和apache Fileupload完成異步上傳文件示例

編輯:關於JAVA

jquery uploadify和apache Fileupload完成異步上傳文件示例。本站提示廣大學習愛好者:(jquery uploadify和apache Fileupload完成異步上傳文件示例)文章只能為提供參考,不一定能成為您想要的結果。以下是jquery uploadify和apache Fileupload完成異步上傳文件示例正文


jQuery Uploadify + Apache Fileupload異步上傳文件示例
1、可以限制上傳文件年夜小和類型,實際上任何類型的文件都可以上傳(本身依據api設置裝備擺設便可);
2、後台應用Apache commons-fileupload-1.3.1.jar作為上傳對象包,本示例支撐一次性多文件上傳;
3、文件上傳目次可以隨意率性指定,請在web.xml中設置裝備擺設;
Uploadify api 詳見http://www.uploadify.com/documentation/

FileUploadServlet


package com.xiaoxing.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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;

/**
 * <h1>Apache Fileupload文件上傳(2014-5-3)</h1>
 * <p>1、假如你對本示例感興致並想懂得更多,迎接參加Java私塾在線進修社區(329232140)</p>
 * <p>2、針對這個例子小修小改即可移植到你的現實項目中。</p>
 */
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 7579265950932321867L;

    // 設置文件默許上傳目次(假如你沒有在web.xml中設置裝備擺設的話)
    private String uploadDir = "c:/"; // 文件上傳目次
    private String tempUploadDir = "c:/"; // 文件暫時寄存目次(會話燒毀後由監聽器主動刪除)

    /*
     * (non-Javadoc)
     * @see javax.servlet.GenericServlet#init()
     * 假如在web.xml中設置裝備擺設了文件上傳目次則優先應用,斷定文件目次能否存在,不存在就創立。
     */
    @Override
    public void init() throws ServletException {
        // 獲得本項目地點真實硬盤目次
        String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(0, path.indexOf("WEB-INF"));
        // 斷定目的能否存在,不存在就樹立
        String uploadDir = path.concat(this.getInitParameter("uploadDir"));
        String tempUploadDir = path.concat(this.getInitParameter("tempUploadDir"));
        File f_uploadDir = new File(uploadDir);
        File f_tempUploadDir = new File(tempUploadDir);
        if (!f_uploadDir.exists()) {
            f_uploadDir.mkdirs();
        }
        if (!f_tempUploadDir.exists()) {
            f_tempUploadDir.mkdirs();
        }
        // 給變量賦值
        this.uploadDir = uploadDir;
        this.tempUploadDir = tempUploadDir;
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     * 不吸收get方法提交的數據,前往上傳掉敗狀況碼。
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.setResponse(response);
        PrintWriter out = response.getWriter();
        out.print("{\"error\":\"-1\""); // 不法提交方法
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     * 上傳文件要求都是平日POST提交
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.setResponse(response); // 設置呼應類型,以便前端解析
        PrintWriter out = response.getWriter();
        String result = "";
        try {
            // 檢討本次能否一個文件上傳要求
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                DiskFileItemFactory factory = new DiskFileItemFactory(); // 創立一個工場基於磁盤的文件項
                factory.setRepository(new File(tempUploadDir)); // 設置裝備擺設貯存庫(確保平安的暫時地位時)
                ServletFileUpload upload = new ServletFileUpload(factory); // 創立一個新的文件上傳處置法式
                upload.setSizeMax(1024 * 1024 * 100); // 設置整體請求尺寸限制(建議前後台分離設置,由於前後台用到了分歧的插件)
                List<FileItem> items = upload.parseRequest(request); // 解析要求
                Iterator<FileItem> iter = items.iterator(); // 處置上傳的項目
                while (iter.hasNext()) { //假如是一次性上傳多個文件,那這裡會分離去保留
                    FileItem item = iter.next();
                    if (!item.isFormField()) { // 過濾表單裡的非文件類型字段
                        if (!"".equals(item.getName())) { // 過濾非文件類型的input
                            String s_name = item.getName(); // 取得原始文件名
                            int position = s_name.lastIndexOf(".");
                            String s_fileType = s_name.substring(position, s_name.length()); // 取得文件後綴
                            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
                            String s = uploadDir.concat("/").concat(date).concat("/");
                            //這裡按日期分目次保留文件
                            File sf = new File(s);
                            if (!sf.exists()) {
                                sf.mkdirs();
                            }
                            String s_filePath = s.concat(UUID.randomUUID().toString()).concat(s_fileType);
                            File path = new File(s_filePath);
                            item.write(path);
                            result += s_filePath.concat(",");
                        } else {
                            result = "";
                            break;
                        }
                    }
                }
            } else {
                result = "";
            }
            String s_resultJSON = this.jointJSON(result); // 拼接前往前端JSON
            out.print(s_resultJSON);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

    /**
     * 拼接JSON,將保留文件的文件名和日期目次前往給前端(前端能夠須要這個途徑完成其他表單操作,好比將文件途徑寄存到數據庫)
     * @param result JSON格局的字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    private String jointJSON (String result) throws UnsupportedEncodingException {
        String str = "";
        if(!"".equals(result)) {
            String rs[] = result.split(",");
            StringBuffer buffer = new StringBuffer("{\"rows\":[");
            for (int i = 0; i < rs.length; i++) {
                String s_tmpName = rs[i];
                s_tmpName = s_tmpName.substring(uploadDir.length(), s_tmpName.length());
                buffer.append("{\"name\":\"").append(s_tmpName).append("\"},");
            }
            str = buffer.toString();
            str = str.substring(0, str.length() - 1).concat("]}");
        } else {
            str = "{\"error\":\"-2\""; //上傳掉敗
        }
        return str;
    }

    /**
     * 設置呼應類型ContentType為"application/x-json"
     * @param response
     */
    private void setResponse(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("cache-control", "no-cache");
    }

}

test_upload.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Uploadify + Apache Fileupload異步上傳文件示例(2014-5-3)</title>
<link rel="stylesheet" type="text/css" href="/js/uploadify/uploadify.css">
<script src="/js/jquery-1.9.0.js"></script>
<script src="/js/uploadify/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
 $('#fileupload').uploadify({
     'method'   : 'post',
     'buttonText' : 'flash上傳文件',
     'fileSizeLimit' : '1024KB',
     'fileTypeExts' : '*.gif; *.jpg; *.png',
  'swf'      : '/js/uploadify/uploadify.swf',
  'uploader' : '/upload', //這是上傳圖片的途徑,也就是我在web.xml裡設置裝備擺設的servlet
  'onUploadSuccess' : function(file, data, response) { //圖片上傳勝利後前往數據在這裡處置
      var ary = eval("(" + data + ")").rows;
      for(var i = 0; i < ary.length; i++) {
          $("#J_div").append("<img alt='圖片' src='/upload/images" + ary[i].name + "' width='200px' height='200px'>");
      }
     }
 });
});
</script>
</head>
<body>
 <h2>jQuery Uploadify + Apache Fileupload異步上傳文件示例(2014-5-3)</h2>
 <p>1、可以限制上傳文件年夜小和類型,實際上任何類型的文件都可以上傳(本身依據api設置裝備擺設便可);</p>
 <p>2、後台應用Apache commons-fileupload-1.3.1.jar作為上傳對象包,本示例支撐一次性多文件上傳;</p>
 <p>3、文件上傳目次可以隨意率性指定,請在web.xml中設置裝備擺設;</p>
 <p>4、關於曾經上傳的圖片沒有查詢到這個頁面上,這部門留給你去做吧。</p>
 <p>Uploadify api 詳見http://www.uploadify.com/documentation/</p>
 <p >*假如你對本示例感興致並想懂得更多,迎接參加Java私塾在線進修社區(329232140)。</p>
 <input id="fileupload" type="file" name="img" multiple="multiple"/>
 <div id="J_div"></div>
</body>
</html>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
  <welcome-file-list>
   <welcome-file>test_upload.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <description>專門用來處置上傳操作的servlet</description>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.xiaoxing.upload.FileUploadServlet</servlet-class>
        <init-param>
         <description>文件寄存的正式目次,可以本身設置裝備擺設</description>
         <param-name>uploadDir</param-name>
         <param-value>/upload/images/</param-value>
        </init-param>
        <init-param>
         <description>文件寄存的暫時目次,可以本身設置裝備擺設,裡的文件由上面設置裝備擺設的監聽器主動刪除。</description>
         <param-name>tempUploadDir</param-name>
         <param-value>/upload/temp</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    <listener>
     <description>暫時文件資本清算,對象包自帶,不消我們來寫</description>
     <listener-class>org.apache.commons.fileupload.servlet.FileCleanerCleanup</listener-class>
   </listener>

</web-app>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved