jquery ajaxfileupload异步上传插件


Posted in jQuery onNovember 21, 2017

本文实例为大家分享了ajaxfileupload异步上传插件的使用方法,供大家参考,具体内容如下

服务器端采用struts2来处理文件上传。

所需环境:
jquery.js
ajaxfileupload.js
struts2所依赖的jar包
及struts2-json-plugin-2.1.8.1.jar

编写文件上传的Action

package com.ajaxfile.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

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 = "你已成功上传文件";
  
  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");

    try {
      File f = this.getFile();
      if(this.getFileFileName().endsWith(".exe")){
        message="对不起,你上传的文件格式不允许!!!";
        return ERROR;
      }
      FileInputStream inputStream = new FileInputStream(f);
      FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getFileFileName());
      byte[] buf = new byte[1024];
      int length = 0;
      while ((length = inputStream.read(buf)) != -1) {
        outputStream.write(buf, 0, length);
      }
      inputStream.close();
      outputStream.flush();
    } catch (Exception e) {
      e.printStackTrace();
      message = "对不起,文件上传失败了!!!!";
    }
    return SUCCESS;
  }

}

struts.xml

<?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" extends="json-default">
    <action name="fileUploadAction" class="com.ajaxfile.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>

注意结合Action观察struts.xml中result的配置。

contentType参数是一定要有的,否则浏览器总是提示将返回的JSON结果另存为文件,不会交给ajaxfileupload处理。这是因为struts2 JSON Plugin默认的contentType为application/json,而ajaxfileupload则要求为text/html。

文件上传的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</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:'fileUploadAction.action',//用于文件上传的服务器端请求地址
        secureuri:false,//一般设置为false
        fileElementId:'file',//文件上传空间的id属性 <input type="file" id="file" name="file" />
        dataType: 'json',//返回值类型 一般设置为json
        success: function (data, status) //服务器成功响应处理函数
        {
          alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量
          
          if(typeof(data.error) != 'undefined')
          {
            if(data.error != '')
            {
              alert(data.error);
            }else
            {
              alert(data.message);
            }
          }
        },
        error: function (data, status, e)//服务器响应失败处理函数
        {
          alert(e);
        }
      }
    )
    
    return false;

  }
  </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="return ajaxFileUpload();">
  </body>
</html>

注意观察<body>中的代码,并没有form表单。只是在按钮点击的时候触发ajaxFileUpload()方法。需要注意的是js文件引入的先后顺序,ajaxfileupload.js依赖于jquery因此你知道的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

jQuery 相关文章推荐
jquery处理checkbox(复选框)是否被选中实例代码
Jun 12 jQuery
详解jQuery同步Ajax带来的UI线程阻塞问题及解决办法
Aug 09 jQuery
使用jquery+iframe做一个ajax上传效果(实例)
Aug 24 jQuery
bootstrap可编辑下拉框jquery.editable-select
Oct 12 jQuery
jQuery简单实现对数组去重及排序操作实例
Oct 31 jQuery
jQuery实现手机号正则验证输入及自动填充空格功能
Jan 02 jQuery
jQuery实现表单动态加减、ajax表单提交功能
Jun 08 jQuery
jQuery中$原理实例分析
Aug 13 jQuery
使用jQuery动态设置单选框的选中效果
Dec 06 jQuery
JavaScript自动生成 年月范围 选择功能完整示例【基于jQuery插件】
Sep 03 jQuery
jquery html添加元素/删除元素操作实例详解
May 20 jQuery
jQuery实现飞机大战小游戏
Jul 05 jQuery
jquery中有哪些api jQuery主要API
Nov 20 #jQuery
jquery ztree实现右键收藏功能
Nov 20 #jQuery
jQuery实现checkbox的简单操作
Nov 18 #jQuery
基于jquery实现五星好评
Nov 18 #jQuery
jQuery实现滚动效果
Nov 17 #jQuery
基于jQuery实现定位导航位置效果
Nov 15 #jQuery
前端html中jQuery实现对文本的搜索功能并把搜索相关内容显示出来
Nov 14 #jQuery
You might like
php include加载文件两种方式效率比较
2010/08/08 PHP
用Javascript同时提交多个Web表单的方法
2009/12/26 Javascript
JavaScript 字符串处理函数使用小结
2010/12/02 Javascript
javascript中动态函数用法实例分析
2015/05/14 Javascript
jQuery超酷平面式时钟效果代码分享
2020/03/30 Javascript
Bootstrap table表格简单操作
2017/02/07 Javascript
jQuery EasyUI 为Combo,Combobox添加清除值功能的实例
2017/04/13 jQuery
JavaScript实现的冒泡排序法及统计相邻数交换次数示例
2017/04/26 Javascript
Angular实现点击按钮控制隐藏和显示功能示例
2017/12/29 Javascript
js中let和var定义变量的区别
2018/02/08 Javascript
详解基于Vue2.0实现的移动端弹窗(Alert, Confirm, Toast)组件
2018/08/02 Javascript
详解Ubuntu安装angular-cli遇到的坑
2018/09/08 Javascript
JS document form表单元素操作完整示例
2020/01/13 Javascript
JS如何把字符串转换成json
2020/02/21 Javascript
[00:56]2014DOTA2国际邀请赛 DK、iG 赛前探访
2014/07/10 DOTA
Python Matplotlib库入门指南
2015/05/18 Python
Python聊天室实例程序分享
2016/01/05 Python
关于Python中异常(Exception)的汇总
2017/01/18 Python
Pycharm学习教程(5) Python快捷键相关设置
2017/05/03 Python
python实现批量修改文件名代码
2017/09/10 Python
python队列通信:rabbitMQ的使用(实例讲解)
2017/12/22 Python
python使用原始套接字发送二层包(链路层帧)的方法
2019/07/22 Python
python 实现ping测试延迟的两种方法
2020/12/10 Python
采用专利算法搜索最廉价的机票:CheapAir
2016/09/10 全球购物
英国IT硬件供应商,定制游戏PC:Mesh Computers
2019/03/28 全球购物
乌克兰电子产品和家用电器购物网站:TOUCH
2019/08/09 全球购物
大学军训感言1000字
2014/02/25 职场文书
霸气队列口号
2014/06/18 职场文书
创新社会管理心得体会
2014/09/12 职场文书
简单通用的简历自我评价
2014/09/21 职场文书
庆祝教师节标语
2014/10/09 职场文书
六一晚会主持词开场白
2015/05/28 职场文书
初中化学教学反思
2016/02/22 职场文书
python - timeit 时间模块
2021/04/06 Python
python爬虫请求库httpx和parsel解析库的使用测评
2021/05/10 Python
漫画《尖帽子的魔法工坊》宣布动画化
2022/04/06 日漫