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>    
复制代码

 提示上传进度改动:

[java]  view plain copy
  1. 取消用  
  2. $("#loading")  
  3.         .ajaxStart(function(){  
  4.             $(this).show();  
  5.         })  
  6.         .ajaxComplete(function(){  
  7.             $(this).hide();  
  8.         });  
  9. ajaxStart为全局注册函数,会产出缓存一直执行!!!!  
  10.   
  11.   
  12. //上传附件  
  13.             function uploadAttachment(n) {  
  14.                 var af = $('#attachmentFile'+n);  
  15.                 if(af.val()=='') {  
  16.                     alert('请选择要上传的文件');  
  17.                     return;  
  18.                 }  
  19.                 $("#attloading"+n).show();  
  20.                 var attNames = $('#attachmentNames'+n).val();  
  21.                   
  22.                 var url = "${ctx}/system/CommonUpload/attachmentUpload.do";  
  23.                 $.ajaxFileUpload( {  
  24.                     url : url,   
  25.                     secureuri : false,  
  26.                     fileElementId : "attachmentFile"+n,   
  27.                     data:{attachmentNames:attNames},  
  28.                     dataType : "json",  
  29.                     success : function(data, status) {  
  30.                         if(data.msg==1){  
  31.                             alert("文件格式不正确(必须为.doc/.docx/.ppt/.xls/.txt/.pdf/.rar文件)");  
  32.                             $('#attachmentFile'+n).val("");  
  33.                             $('#attachmentText'+n).val("");  
  34.                         }else if(data.msg==2){  
  35.                             alert("文件太大!请重新选择");  
  36.                             $('#attachmentFile'+n).val("");  
  37.                             $('#attachmentText'+n).val("");  
  38.                         }else if(data.msg==0){  
  39.                             $('#attachmentFile'+n).val("");  
  40.                             $('#attachmentText'+n).val("");  
  41.                             $('#attIds'+n).val(data.attId);  
  42.                             $('#attachmentNames'+n).val(data.attachmentextFileName);  
  43.                             alert("上传成功!");  
  44.                         }  
  45.                     },complete: function(XMLHttpRequest, status){  
  46.                         alert("hide");  
  47.                         $("#attloading"+n).hide();  
  48.                     },  
  49.                     error : function(data, status, e){  
  50.                         alert(e);  
  51.                     }  
  52.                 });  
  53.             }  
  54. //使用这两个方法  
[java]  view plain copy
  1. $("#attloading"+n).show();  
[java]  view plain copy
  1. complete: function(XMLHttpRequest, status){  
  2.                         alert("hide");  
  3.                         $("#attloading"+n).hide();  
  4.                     },  

定义和用法

ajaxStart() 方法在 AJAX 请求发送前执行函数。它是一个 Ajax 事件。

详细说明

无论在何时发送 Ajax 请求,jQuery 都会检查是否存在其他 Ajax 请求。如果不存在,则 jQuery 会触发该 ajaxStart 事件。在此时,由 .ajaxStart() 方法注册的任何函数都会被执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值