springboot实现文件上传

表单方式

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Index</title>
</head>
<body>
<form action="/load" method="post" enctype="multipart/form-data">
    <input type="file" name="file2"><br>
    <input type="submit" value="文件上传">
</form>

</body>
</html>
@Controller
public class HelloController {

    @PostMapping("/load")
    @ResponseBody
    // 当 <input type="file" name="file2"> 的 name 不是 file 的时候,需要 @RequestAttribute
    public String load(@RequestAttribute("file2") MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            try {
                File f = new File("E:/", Objects.requireNonNull(file.getOriginalFilename()));
                file.transferTo(f);
                return "ok";
            } catch (Exception e) {
                return "error";
            }
        }
        return "error";
    }
}

官网使用的是 @RequestPart 注解,这里也推荐这种方式

public class HelloController {

    @PostMapping("/load")
    @ResponseBody
    public String load(@RequestPart("file2") MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            try {
                File f = new File("E:/", Objects.requireNonNull(file.getOriginalFilename()));
                file.transferTo(f);
                return "ok";
            } catch (Exception e) {
                return "error";
            }
        }
        return "error";
    }
}

axios 方式

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Index</title>
    <script src="/webjars/axios/0.21.1/dist/axios.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<input type="button" value="上传" id="btn">
<script>
    let btn = document.getElementById("btn");
    btn.onclick = function () {
        // 获取 FileList
        let files = document.getElementById("file").files;
        // 构建表单
        let formData = new FormData();
        formData.append("file", files[0]);
        // 添加其他属性
        formData.append("name", "tom");
        axios({
            method: 'post',
            url: '/hello',
            // 设置头文件
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: formData
        }).then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err);
        });
    };
</script>
</body>
</html>
@RestController
public class HelloController {

    @PostMapping(value = {"/", "/hello"})
    public String hello(MultipartFile file, String name) {
        if (file != null && !file.isEmpty()) {
            System.out.println("name: " + name);
            return file.getOriginalFilename();
        }
        return "hello world";
    }
}
  • 可以不使用 MultipartFile,直接通过 HttpServletRequest 获取 getPart(getParts()) 来自己实现,但没必要
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值