springboot用户上传图片

前端

图片上传.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>图片上传title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
head>
<body>
<form id="uploadForm" enctype="multipart/form-data" th:action="@{/toAdd}" method="post"
                      th:onsubmit="return toSubmit()">

    <input accept="image/*" type="file" name="file" v-model="pic" />
     <br>
    <input type="submit" name="提交">
form>

<script> function toSubmit() { var form = document.getElementById("uploadForm"); let formData = new FormData(form); if (formData.get("img").size > 1024 * 1024) { alert("图片过大,请提交图片截屏或者选择小于1M的图片!"); return false; } else { return true; } } script> body> html>

后端:

LoginController.java
@Controller
public class LoginController {
    @RequestMapping("/upload12")
    public String upload12() {
        return "图片上传"; //就是返回以上的html的名字
    }

    @ResponseBody
    @PostMapping("/upload")
    public String upload2(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();

        String filePath = "/Users/mac/Desktop/未命名文件夹";
        if (file.isEmpty()) {
            return "文件为空!";
        }

        try {
            uploadFile(file.getBytes(), filePath, getUUID());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传成功!";   // 前后端分离,则返回json
    }

    // 写入文件,filepath是文件路径【tomcat默认的文件上传大小是1M,如果想要修改,需要添加配置文件】
    public static void uploadFile(byte[] file, String filePath, String filename) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + "/" + filename + ".png");
        out.write(file);
        out.flush();
        out.close();
    }

    // 同时需要将上传图片的原始文件名和存储文件名、以及关联id存入一个数据表中【这里省略】。
    // 生成uuid
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");
        return uuidStr;
    }

}

用户上传头像-修改1M限制:

Original: https://www.cnblogs.com/cjin-01/p/16721577.html
Author: 2337
Title: springboot用户上传图片

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/711784/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球