【文件上传】前端html上传 + 后端SpringBoot接收并保存

1. 前端页面

<form>记得设置一下enctype = "multipart/form-data"

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04-文件上传</title>
</head>
<body>
  <form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data" align="center">
    <h2>请选择你的文件进行上传吧</h2>
    <input type="file" name="file" multiple> <br>
    <input type="submit" value="上传!~">
  </form>
</body>
</html>

2. 后端核心代码

后端的Controller中接收的类型是MultipartFile

@RestController
public class UploadController {
    @PostMapping("/upload")
    public static Result upload(@RequestParam("file") MultipartFile file) {
    //   public static final String targetFilePath = "E:\\MyDownLoad";
        String des = HtmlConstant.targetFilePath + File.separator + file.getOriginalFilename();
        FileOutputStream fos = null;
        try {
            // 1. 获取输入流
            InputStream inputStream = file.getInputStream();
            // 2. 创建file
            File newFile = new File(des);
            // 3. 获取输出流
            fos = new FileOutputStream(newFile);
            // 4. 使用工具类进行写入
            IOUtils.copy(inputStream, fos);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败,请联系管理员");
        }finally {
            try {
                fos.close(); // 记得关闭,不然文件写入可能不会完成。
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.ok("上传成功了~");
    }
}

3. 其他代码

这里创建了一个DTO (Data Transfer Object) 数据传输对象

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
    private Boolean success;
    private String errorMsg;
    private Object data;

    public static Result ok(){
        return new Result( true,null,null);
    }

    public static Result ok(Object data) {
        return new Result(true, null, data);
    }

    public static Result fail(String errorMsg) {
        return new Result(false, errorMsg, null);
    }

}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值