Home Web Front-end JS Tutorial FormData and Spring MVC implement Ajax file download function

FormData and Spring MVC implement Ajax file download function

Mar 31, 2018 am 10:39 AM
ajax formdata spring

This time I will bring you FormData and Spring MVC to implement the Ajax file download function. What are the precautions for FormData and Spring MVC to implement the Ajax file download function. The following is a practical case. , let’s take a look.

Ajax file download

Using the FormData object and Spring MVC to implement the Ajax file upload function:

Steps

1. Import components and prepare static scripts

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.2</version>
</dependency>
  <h1>Ajax 文件上载</h1>
  <input type="file" id="file1"> <br>
  <input type="file" id="file2"> <br>
  <input type="button" id="upload" value="上载" >
  <p id="result"></p>
Copy after login
1. Bind events to buttons

$("upload").click(ajaxUpload);
Copy after login
2. Get files

var file1 = $("#file1")[0].files[0];
var file2 = $("#file2")[0].files[0];
Copy after login
3. Create the form object in memory and add the data transmitted to the server

//创建内存中的表单对象
var form = new FormData();
//向其中添加要传输的数据
form.append("userfile1", file1);
form.append("userfile2", file2);
Copy after login
4.ajax() upload object

$.ajax({
  url:'user/upload.do',//请求地址
  data: form,   //请求参数
  type: 'POST',  //请求类型
  dataType: 'json',//服务器返回的数据类型
  contentType: false,//没有设置任何内容类型头信息
  processData: false, //见jQuery_api详解
  success: function(obj){ //成功时回调函数,obj表示服务器返回的数据
    if(obj.state==0){
      $('#result').html("成功!"); 
    }
  }
});
Copy after login
5.Spring-MVC presentation layer

@RequestMapping("/upload.do")
@ResponseBody
public JsonResult upload( 
    MultipartFile userfile1, 
    MultipartFile userfile2) throws Exception{
  //Spring MVC 中可以利用 MultipartFile 
  //接收 上载的文件! 文件中的一切数据
  //都可以从 MultipartFile 对象中找到
  //获取上再是原始文件名
  String file1 = 
    userfile1.getOriginalFilename();
  String file2 = 
    userfile2.getOriginalFilename();
  System.out.println(file1);
  System.out.println(file2);
  //保存文件的3种方法:
  //1. transferTo(目标文件)
  //  将文件直接保存到目标文件, 可以处理大文件
  //2. userfile1.getBytes() 获取文件的全部数据
  //  将文件全部读取到内存, 适合处理小文件!!
  //3. userfile1.getInputStream()
  //  获取上载文件的流, 适合处理大文件
  //保存的目标文件夹: /home/soft01/demo
  File dir = new File("D:/demo");
  dir.mkdir();
  File f1 = new File(dir, file1);
  File f2 = new File(dir, file2);
  //第一种保存文件
  //userfile1.transferTo(f1);
  //userfile2.transferTo(f2);
  //第三种 利用流复制数据
  InputStream in1 = userfile1.getInputStream();
  FileOutputStream out1 = 
    new FileOutputStream(f1);
  int b;
  while((b=in1.read())!=-1){
    out1.write(b);
  }
  in1.close();
  out1.close();
  InputStream in2 = userfile2.getInputStream();
  FileOutputStream out2=
      new FileOutputStream(f2);
  byte[] buf= new byte[8*1024];
  int n;
  while((n=in2.read(buf))!=-1){
    out2.write(buf, 0, n);
  }
  in2.close();
  out2.close();
  return new JsonResult(true);
  }
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to implement WebApi Ajax cross-domain requests using CORS

How to implement dynamic loading of combo boxes with Ajax (With code)

The above is the detailed content of FormData and Spring MVC implement Ajax file download 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)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

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.

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

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

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

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:

See all articles