Home Web Front-end JS Tutorial AjaxFileUpload+Struts2 implements multi-file upload function

AjaxFileUpload+Struts2 implements multi-file upload function

May 21, 2018 pm 05:22 PM
upload Function

这篇文章主要介绍了AjaxFileUpload+Struts2实现多文件上传功能,需要的朋友可以参考下

本文重点给大家介绍AjaxFileUpload+Struts2实现多文件上传功能,具体实现代码大家参考下本文。

单文件和多文件的实现区别主要修改两点,

一是插件ajaxfileupload.js里接收file文件ID的方式

二是后台action是数组形式接收

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

2、引入jquery-1.8.0.min.js、ajaxFileUpload.js文件

3、文件上传页面核心代码

<body> 
  <form action="" enctype="multipart/form-data"> 
    <h2> 
      多文件上传 
    </h2> 
    <input type="file" id="file1" name="file" /> 
    </br> 
    <input type="file" id="file2" name="file" /> 
    </br> 
    <input type="file" id="file3" name="file" /> 
    </br> 
    <span> 
      <table id="down"> 
      </table> 
    </span> 
    </br> 
    <input type="button" onclick="fileUpload();" value="上传"> 
  </form> 
</body> 
<script type="text/javascript"> 
  function fileUpload() { 
    var files = ['file1','file2','file3']; //将上传三个文件 ID 分别为file2,file2,file3 
    $.ajaxFileUpload( { 
      url : 'fileUploadAction',   //用于文件上传的服务器端请求地址  
      secureuri : false,      //一般设置为false  
      fileElementId : files,    //文件上传的id属性 <input type="file" id="file" name="file" />  
      dataType : 'json',      //返回值类型 一般设置为json  
      success : function(data, status) { 
        var fileNames = data.fileFileName; //返回的文件名  
        var filePaths = data.filePath;   //返回的文件地址  
        for(var i=0;i<data.fileFileName.length;i++){ 
          //将上传后的文件 添加到页面中 以进行下载 
          $("#down").after("<tr><td height=&#39;25&#39;>"+fileNames[i]+ 
              "</td><td><a href=&#39;downloadFile?downloadFilePath="+filePaths[i]+"&#39;>下载</a></td></tr>") 
        } 
      } 
    }) 
  } 
</script>
Copy after login

以上fileElementId属性接收的files参数为['file1','file2','file3']

由于是多文件,所以我们需要修改ajaxfileupload.js 找到以下代码

var oldElement = jQuery('#' + fileElementId); 
var newElement = jQuery(oldElement).clone(); 
jQuery(oldElement).attr('id', fileId); 
jQuery(oldElement).before(newElement); 
jQuery(oldElement).appendTo(form);
Copy after login

修改为:

for(var i in fileElementId){  
  var oldElement = jQuery('#' + fileElementId[i]);  
  var newElement = jQuery(oldElement).clone();  
  jQuery(oldElement).attr('id', fileId);  
  jQuery(oldElement).before(newElement);  
  jQuery(oldElement).appendTo(form);  
}
Copy after login

4、文件上传Action

public class FileAction { 
  private File[] file;       //文件  
  private String[] fileFileName;  //文件名   
  private String[] filePath;    //文件路径 
  private String downloadFilePath; //文件下载路径 
  private InputStream inputStream;  
  /** 
   * 文件上传 
   * @return 
   */ 
  public String fileUpload() { 
    String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
    File file = new File(path); // 判断文件夹是否存在,如果不存在则创建文件夹 
    if (!file.exists()) { 
      file.mkdir(); 
    } 
    try { 
      if (this.file != null) { 
        File f[] = this.getFile(); 
        filePath = new String[f.length]; 
        for (int i = 0; i < f.length; i++) { 
          String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名 
          String name = fileName + fileFileName[i].substring(fileFileName[i].lastIndexOf(".")); //保存在硬盘中的文件名 
          FileInputStream inputStream = new FileInputStream(f[i]); 
          FileOutputStream outputStream = new FileOutputStream(path+ "\\" + name); 
          byte[] buf = new byte[1024]; 
          int length = 0; 
          while ((length = inputStream.read(buf)) != -1) { 
            outputStream.write(buf, 0, length); 
          } 
          inputStream.close(); 
          outputStream.flush(); 
          //文件保存的完整路径 
          // 如:D:\tomcat6\webapps\struts_ajaxfileupload\\upload\a0be14a1-f99e-4239-b54c-b37c3083134a.png 
          filePath[i] = path + "\\" + name; 
        } 
      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
    return "success"; 
  } 
  /** 
   * 文件下载 
   * @return 
   */ 
  public String downloadFile() { 
    String path = downloadFilePath; 
    HttpServletResponse response = ServletActionContext.getResponse(); 
    try { 
      // path是指欲下载的文件的路径。 
      File file = new File(path); 
      // 取得文件名。 
      String filename = file.getName(); 
      // 以流的形式下载文件。 
      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; 
  } 
  /** 
   * 省略set get方法 
   */ 
}
Copy after login

5、struts配置

<!DOCTYPE struts PUBLIC  
  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
  "http://struts.apache.org/dtds/struts-2.0.dtd"> 
<struts> 
  <package name="ajax_code" extends="json-default"> 
    <!-- 文件上传 --> 
    <action name="fileUploadAction" class="com.itmyhome.FileAction" method="fileUpload"> 
      <result type="json" name="success"> 
        <param name="contentType">text/html</param> 
      </result> 
    </action> 
  </package> 
  <package name="jsp_code" extends="struts-default"> 
    <!-- 文件下载 -->    
    <action name="downloadFile" class="com.itmyhome.FileAction" method="downloadFile">   
      <result type="stream">   
         <param name="contentType">application/octet-stream</param>   
         <param name="inputName">inputStream</param>   
         <param name="contentDisposition">attachment;filename=${fileName}</param>   
         <param name="bufferSize">4096</param>   
      </result>   
    </action>  
  </package> 
</struts>
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

利用ajax提交form表单到数据库详解(无刷新)

基于Ajax和forms组件实现注册功能(含有代码)

ajax 实现微信网页授权登录的方法(图文教程)

The above is the detailed content of AjaxFileUpload+Struts2 implements multi-file upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What functions does Doubao app have? What functions does Doubao app have? Mar 01, 2024 pm 10:04 PM

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

What is a Bluetooth adapter used for? What is a Bluetooth adapter used for? Feb 19, 2024 pm 05:22 PM

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

See all articles