• 文件上传功能实现


    很多小伙伴会遇到图片上传的功能,下面给大家分享图片上传的具体代码实现。话不多,直接上代码:
    package org.example.demo2.config;

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.StringUtils;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.File;
    import java.io.IOException;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.HashMap;
    import java.util.Map;

    @CrossOrigin(origins ="*")
    @RestController
    @RequestMapping("/param")
    @Validated
    public class FileParamController{

        @PostMapping("/upload")
        public String uploadFile(@RequestParam("file") MultipartFile file) {
            String uploadFile = "C:\\upload\\images";
            // 1:指定文件上传的目录

            //获取当前年月
            // 获取当前年月
            LocalDate now = LocalDate.now();
            String yearMonth = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
            uploadFile=uploadFile+"\\"+yearMonth;
            File targetFile = new File(uploadFile);
            try {
                // 2:如果targetFile不存在,则创建
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 3: 指定文件上传后的目录
                String fileName = file.getOriginalFilename();
                File targetFileName = new File(targetFile, fileName); // 先写死
                // 4:文件上传到指定的目录
                file.transferTo(targetFileName);

                Map map=new HashMap<>();
                map.put("filename",fileName);
                map.put("code",200);
                return "/FinforWorx/images/"+yearMonth+"/"+fileName;
            } catch (IOException e) {
                e.printStackTrace();
                Map map=new HashMap<>();
                map.put("des","上传错误");
                map.put("code",500);
                return "上传错误";
            }
        }
    }

  • 相关阅读:
    Https的1.0、2.0协议及长短链接区别
    C/C++变长参数
    【银角大王——Django课程——创建项目+部门表的基本操作】
    应用层协议 HTTP
    GIS地图服务数据可视化
    Mesh快连
    netcore webapi action 同时支持 get 和 post 请求
    XML实体注入漏洞
    Semantic Kernel 入门系列:🛸LLM降临的时代
    走进Flink
  • 原文地址:https://blog.csdn.net/lf21qp/article/details/133770153