• 文件上传功能实现


    很多小伙伴会遇到图片上传的功能,下面给大家分享图片上传的具体代码实现。话不多,直接上代码:
    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 "上传错误";
            }
        }
    }

  • 相关阅读:
    Velox Types介绍和源码解析
    传输层 四层负载均衡可以做什么?
    JUMPSERVER----一键安装
    使用 pubsub-js 进行消息发布订阅
    关于torch.load加载预训练模型时 造成的 临时分配的显存 不释放
    别再当大冤种了,揭开3D建模报班6个常见套路
    HTTP报文首部
    把微信好友不小心删了,有什么办法找回?
    本地运行“李开复”的零一万物 34B 大模型
    YOLOv8+swin_transfomerv2
  • 原文地址:https://blog.csdn.net/lf21qp/article/details/133770153