ajaxFileUpload+struts2實現異步上傳文件

文件上傳在項目中應該是非常常見的,而且很多時候,上傳文件都只是一個小頁面中的一個功能,要求在實現文件上傳的前提下不刷新頁面。而一般情況下將客戶端的文件包裝成網絡地址傳遞到服務器端然後通過流來進行文件傳輸的任務都是使用瀏覽器來幫我們完成的,一般情況下,我們的form表單提交,我們自己可以手動拿到表單的值,然後封裝起來,發送ajax請求,爲了安全着想,js是不允許訪問客戶端的文件系統的,所以而文件傳輸需要瀏覽器來完成,ajax上傳其實是在頁面中一小塊區域加一個iframe對象然後引用到另一個頁面,提交引用的那個頁面。

1、ajaxFileUpload文件下載地址 http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

       http://download.csdn.net/detail/yangfuqian/4337967

2、

jsp頁面 (<input type="file"/>默認的樣式很醜,調整樣式有點小麻煩)

我沒有加表單,ajax提交表單應該沒什麼問題,方法很多網上百度

複製代碼
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
    <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/ajaxfileupload.js"></script>
        <script type="text/javascript">
    function ajaxFileUpload()
    {
        
        $("#loading")
        .ajaxStart(function(){
            $(this).show();
        })//開始上傳文件時顯示一個圖片
        .ajaxComplete(function(){
            $(this).hide();
        });//文件上傳完成將圖片隱藏起來
        
        $.ajaxFileUpload
        (
            {
                url:'fileAction.action',//用於文件上傳的服務器端請求地址
                secureuri:false,//一般設置爲false
                fileElementId:'file',//文件上傳空間的id屬性  <input type="file" id="file" name="file" />
                dataType: 'json',//返回值類型 一般設置爲json
                success: function (data, status)  //服務器成功響應處理函數
                {
                    //從服務器返回的json中取出message中的數據,其中message爲在struts2中定義的成員變量
                    alert(data.message);
                },
                error: function (data, status, e)//服務器響應失敗處理函數
                {
                    alert(e);
                }
            }
        )
    }
    
    function f_DL(){
        location.href="fileAction!download.action?filePath="+"D:\\apache-tomcat-7.0.41\\webapps\\ajaxFileUploadDemo\\upload\\1P5521N4-3.jpg";
    }
    </script>
    </head>
    <body>
        <img src="loading.gif" id="loading" style="display: none;">
        <input type="file" id="file" name="file" />
        <br />
        <input type="button" value="上傳" onclick="ajaxFileUpload();">
        
        <input type="button" value="下載" onclick="f_DL()"/>
    </body>
</html>
複製代碼


3、action

複製代碼
package com.demo.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileAction extends ActionSupport {

    private File file;
    private String fileFileName;
    private String fileFileContentType;
    private String message = "0"; // 0格式錯誤 1成功(文件路徑)  2失敗
    private String filePath;

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileFileContentType() {
        return fileFileContentType;
    }

    public void setFileFileContentType(String fileFileContentType) {
        this.fileFileContentType = fileFileContentType;
    }

    @SuppressWarnings("deprecation")
    @Override
    public String execute() throws Exception {

        String path = ServletActionContext.getRequest().getRealPath("/upload");
        File file = new File(path); // 判斷文件夾是否存在,如果不存在則創建文件夾
        if (!file.exists()) {
            file.mkdir();
        }
        String[] fileSuffix = new String[] { ".exe" };// 禁止文件
        try {
            File f = this.getFile();
            // 判斷文件格式
            for (int i = 0; i < fileSuffix.length; i++) {
                if (fileFileName.endsWith(fileSuffix[i])) {
                    message = "0";
                    return ERROR;
                }
            }
            FileInputStream inputStream = new FileInputStream(f);
            FileOutputStream outputStream = new FileOutputStream(path + "\\"
                    + fileFileName);
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, length);
            }
            inputStream.close();
            outputStream.flush();
            message = path + "\\" + this.getFileFileName();
        } catch (Exception e) {
            e.printStackTrace();
            message = "2";
        }
        return SUCCESS;
    }

    public String download() {
        String path = filePath;
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            // path是指欲下載的文件的路徑。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的後綴名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1)
                    .toUpperCase();

            // 以流的形式下載文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設置response的Header
            String filenameString = new String(filename.getBytes("gbk"),
                    "iso-8859-1");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + filenameString);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response
                    .getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

}
複製代碼

4、struts2配置

複製代碼
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <package name="struts2" namespace="/" extends="json-default">
        <action name="fileAction" class="com.demo.action.FileAction">
            <result type="json" name="success">
                <param name="contentType">
                    text/html
                </param>
            </result>
            <result type="json" name="error">
                <param name="contentType">
                    text/html
                </param>
            </result>
        </action>
    </package>
</struts>    
複製代碼

 提示上傳進度改動:

取消用
$("#loading")
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide();
		});
ajaxStart爲全局註冊函數,會產出緩存一直執行!!!!


//上傳附件
			function uploadAttachment(n) {
				var af = $('#attachmentFile'+n);
				if(af.val()=='') {
					alert('請選擇要上傳的文件');
					return;
				}
				$("#attloading"+n).show();
				var attNames = $('#attachmentNames'+n).val();
				
				var url = "${ctx}/system/CommonUpload/attachmentUpload.do";
				$.ajaxFileUpload( {
					url : url, 
					secureuri : false,
					fileElementId : "attachmentFile"+n, 
					data:{attachmentNames:attNames},
					dataType : "json",
					success : function(data, status) {
						if(data.msg==1){
							alert("文件格式不正確(必須爲.doc/.docx/.ppt/.xls/.txt/.pdf/.rar文件)");
							$('#attachmentFile'+n).val("");
							$('#attachmentText'+n).val("");
						}else if(data.msg==2){
							alert("文件太大!請重新選擇");
							$('#attachmentFile'+n).val("");
							$('#attachmentText'+n).val("");
						}else if(data.msg==0){
							$('#attachmentFile'+n).val("");
							$('#attachmentText'+n).val("");
							$('#attIds'+n).val(data.attId);
							$('#attachmentNames'+n).val(data.attachmentextFileName);
							alert("上傳成功!");
						}
					},complete: function(XMLHttpRequest, status){
						alert("hide");
						$("#attloading"+n).hide();
					},
					error : function(data, status, e){
						alert(e);
					}
				});
			}
//使用這兩個方法
$("#attloading"+n).show();
complete: function(XMLHttpRequest, status){
						alert("hide");
						$("#attloading"+n).hide();
					},



定義和用法

ajaxStart() 方法在 AJAX 請求發送前執行函數。它是一個 Ajax 事件。

詳細說明

無論在何時發送 Ajax 請求,jQuery 都會檢查是否存在其他 Ajax 請求。如果不存在,則 jQuery 會觸發該 ajaxStart 事件。在此時,由 .ajaxStart() 方法註冊的任何函數都會被執行。


發佈了91 篇原創文章 · 獲贊 7 · 訪問量 50萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章