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

2021-06-04 12:01

阅读:462

YPE html>

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

目录
  • 项目
  • 参考

技术图片

项目

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

4.0.0org.springframework.boot
        spring-boot-starter-parent
        2.3.3.RELEASEcom.mk
    spring-boot-XMLHttpRequest-upload
    1.0.0spring-boot-XMLHttpRequest-uploadDemo project for Spring Boot1.8org.springframework.boot
            spring-boot-starter-thymeleaf
        org.springframework.boot
            spring-boot-starter-web
        org.springframework.boot
            spring-boot-devtools
            runtimetrueorg.springframework.boot
            spring-boot-configuration-processor
            trueorg.projectlombok
            lombok
            trueorg.springframework.boot
            spring-boot-starter-test
            testorg.junit.vintage
                    junit-vintage-engine
                commons-io
            commons-io
            2.6org.springframework.boot
                spring-boot-maven-plugin
                org.springframework.boot
                            spring-boot-configuration-processor
                        org.projectlombok
                            lombok
                        

编辑 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 文件:



Using XMLHttpRequest

参考

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


评论


亲,登录后才可以留言!