Home Backend Development PHP Tutorial Detailed example of Ajax's FileUpload and Struts2 implementing multi-file upload function

Detailed example of Ajax's FileUpload and Struts2 implementing multi-file upload function

Dec 25, 2017 am 10:10 AM
ajax fileupload struts2

单文件和多文件的实现区别主要修改两点,一是插件ajaxfileupload.js里接收file文件ID的方式,二是后台action是数组形式接收。本文主要介绍了AjaxFileUpload+Struts2实现多文件上传功能,需要的朋友可以参考下,希望能帮助到大家。

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

浏览器中输入:http://localhost:8080/struts_ajaxfileupload/index.jsp  即可进行文件上传

如图:

相关推荐:

详解ajax fileupload异步上传插件

ajaxfileupload.js上传文件后调用error函数该如何处理

有关FileUpload的10篇内容推荐

The above is the detailed content of Detailed example of Ajax's FileUpload and Struts2 implementing 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

What is the principle of Struts2 framework What is the principle of Struts2 framework Jan 04, 2024 pm 01:55 PM

The principle of the Struts2 framework: 1. The interceptor parses the request path; 2. Finds the complete class name of the Action; 3. Creates the Action object; 4. Execute the Action method; 5. Returns the result; 6. View parsing. Its principle is based on the interceptor mechanism, which completely separates the business logic controller from the Servlet API, improving the reusability and maintainability of the code. By using the reflection mechanism, the Struts2 framework can flexibly create and manage Action objects to process requests and responses.

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Understanding Ajax Frameworks: Explore Five Common Frameworks Understanding Ajax Frameworks: Explore Five Common Frameworks Jan 26, 2024 am 09:28 AM

Understanding the Ajax Framework: Explore five common frameworks, requiring specific code examples Introduction: Ajax is one of the essential technologies in modern web application development. It has become an indispensable part of front-end development because of its features such as supporting asynchronous data interaction and improving user experience. In order to better understand and master the Ajax framework, this article will introduce five common Ajax frameworks and provide specific code examples to help readers gain an in-depth understanding of the usage and advantages of these frameworks. 1. jQuery jQuery is currently the most

See all articles