文件上传功能实现

简介: 文件上传功能实现

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

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 "上传错误";
        }
    }
}
相关文章
|
1月前
|
PHP
thinkphp中自定义文件上传
thinkphp中自定义文件上传
18 0
|
3月前
|
存储
若依框架 --- pdf文件上传预览功能实现
若依框架 --- pdf文件上传预览功能实现
154 0
|
4月前
|
开发框架 移动开发 小程序
uniapp实现上传文件功能
uniapp实现上传文件功能
195 0
|
6月前
|
网络协议
|
5月前
|
Web App开发 前端开发 测试技术
postman测试上传图片接口步骤教程
postman测试上传图片接口步骤教程
162 0
|
7月前
|
数据库
对象管理器设计-ConnectionManager 文件上传题 1. 对象管理器设计
对象管理器设计-ConnectionManager 文件上传题 1. 对象管理器设计
|
10月前
|
存储 前端开发 JavaScript
后端文件上传以及下载功能实现
上一章讲到前端文件下载功能的实现,之前也讲过前端文件上传功能的实现,这一章就讲一下后端怎么接收前端上传的文件,以及怎么实现文件下载功能。
294 0
|
存储 测试技术
接口自动化测试——文件上传/下载
轻松搞定文件上传接口和文件下载接口。
241 0
接口自动化测试——文件上传/下载
|
存储 前端开发 应用服务中间件
关于项目中文件上传
关于项目中文件上传
190 0
|
前端开发
前端项目实战100-控制上传文件只能上传一个
前端项目实战100-控制上传文件只能上传一个
141 0