码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot - XMLHttpRequest Upload(上传文件,非前后端分离)

时间:2021-04-14 12:33:52      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:start   des   test   ade   rip   aml   event   lse   xmlhttp   

技术图片

项目

新建 Spring Starter Project,编辑 pom.xml 文件,引入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.mk</groupId>
    <artifactId>spring-boot-XMLHttpRequest-upload</artifactId>
    <version>1.0.0</version>

    <name>spring-boot-XMLHttpRequest-upload</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Commons IO -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

编辑 application.yml 文件,设置上传文件的大小限制:

spring:
  servlet:
    multipart:
      max-file-size: 200MB
      max-request-size: 1000MB

IndexController 控制器:

package com.mk.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class IndexController {

    @GetMapping({"", "/index"})
    public String index() {
        return "index";
    }
    
    @PostMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest request,
            @RequestParam(value = "file", required = false) MultipartFile file,
            String filename) throws IllegalStateException, IOException {
        
        String authorization = request.getHeader("Authorization");
        System.out.println(authorization);
        
        String originalFilename = file.getOriginalFilename();
        file.transferTo(new File("G:/20191212", originalFilename));
        
        return filename;
    }
}

src/main/resources/templates/index.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Using XMLHttpRequest</title>
    </head>
    <body>
        <input type="file" accept="*.*" />

        <script type="text/javascript">
            window.onload = (event) => {
                const DONE = 4
                
                const input = document.querySelector(‘input[type=file]‘)
                
                input.onchange = (event) => {
                    const files = event.target.files
                    
                    if (files.length > 0) {
                        const file = files[0]
                        console.log(file)
                        
                        const formData = new FormData()
                        formData.append(‘filename‘, file.name)
                        formData.append(‘file‘, files[0])
                        
                        const xhr = new XMLHttpRequest()
                        xhr.addEventListener("load", function(event) {
//                             console.log(event)
                            if (xhr.readyState == DONE && xhr.status == 200) {
                                console.log(xhr)
                                console.log(xhr.response)
                            }
                        })
                        xhr.open("POST", "/upload", true)
                        xhr.responseType = ‘text‘
                        xhr.setRequestHeader(‘Authorization‘, ‘1234567890‘)
                
                        xhr.send(formData)
                    }
                }
            }
        </script>
    </body>
</html>

参考

XMLHttpRequest

4.5. Handling Multipart File Uploads

Spring Boot - XMLHttpRequest Upload(上传文件,非前后端分离)

标签:start   des   test   ade   rip   aml   event   lse   xmlhttp   

原文地址:https://www.cnblogs.com/Satu/p/14656024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!