Spring Boot - XMLHttpRequest Upload(带请求头上传文件,非前后端分离)
发布日期:2021-05-06 23:03:02 浏览次数:14 分类:技术文章

本文共 3616 字,大约阅读时间需要 12 分钟。

文章目录

在这里插入图片描述

项目

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

4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.3.RELEASE
com.mk
spring-boot-XMLHttpRequest-upload
1.0.0
spring-boot-XMLHttpRequest-upload
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
true
org.springframework.boot
spring-boot-configuration-processor
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
commons-io
commons-io
2.6
org.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;@Controllerpublic 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

参考

上一篇:Spring Boot - axios upload file(带请求头上传文件,非前后端分离)
下一篇:Web API - File - Using object URLs to display PDF

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年03月09日 19时09分52秒