SpringBoot实现文件上传

一、Controller层

首先创建一个SpringBoot项目,然后编写一个接收前端请求的Controller层,如下

package com.aiun.product.controller;
/**
 * @author lenovo
 */
@Api(tags = "上传文件相关接口")
@Controller
public class UpLoadController {
    /**
     * 获取file.html页面
     * @return 跳转到 file 页面
     */
    @GetMapping("/file")
    @ApiOperation(value = "获取file.html页面, 进行上传文件操作")
    public String file(){
        return "file";
    }
}

@Api和@ApiOperation注解是用于Swagger接口文档的描述,访问localhost:8083/backend-product/file接口,返回一个html页面,该页面在src/main/resources/templates/file.html下

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="product/manage/upload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="upload_file"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>

点击提交会跳转到product/manage/upload接口,该接口我定义在ProductController类里,如下:

package com.aiun.product.controller;

/**
 * 产品控制层
 * @author lenovo
 */
@Api(tags = "产品相关接口")
@RestController
@RequestMapping("/product/")
public class ProductController {
    @Value("${image.localhost}")
    private String mageHost;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IFileService iFileService;

    /**
     * 文件上传
     * @param file 文件
     * @return 返回给前端的信息
     */
    @PostMapping("manage/upload")
    @ApiOperation(value = "文件上传", notes = "文件上传")
    public ServerResponse upload(@RequestParam(value = "upload_file", required = false) MultipartFile file) {
        String targetFileName = iFileService.upload(file, mageHost);
        String url =  mageHost + targetFileName;

        Map fileMap = Maps.newHashMap();
        fileMap.put("uri", targetFileName);
        fileMap.put("url", url);

        return ServerResponse.createBySuccess(fileMap);
    }
}

@Value("${image.localhost}") 注解用于从application.yml文件获取图片的存储位置
然后调用IFileService,看IFileService的实现类FileServiceImpl

package com.aiun.product.service.impl;
/**
 * 文件上传
 * @author lenovo
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService {
    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Override
    public String upload(MultipartFile file, String path) {
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID() + "." + fileExtensionName;

        logger.info("开始上传文件,上传的文件名:{},上传的路径:{},新文件名:{}", fileName, path, uploadFileName);
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            // 赋予写权限
            fileDir.setWritable(true);
            // 递归创建目录
            fileDir.mkdirs();
        }
        File targetFile = new File(path, uploadFileName);
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            logger.error("上传文件异常", e);
            return null;
        }
        return targetFile.getName();
    }
}

上传成功后会返回图片的 uri 和 url。
接下来进入到Spring Boot的启动类,启动该项目
访问http://localhost:8083/backend-product/file接口
在这里插入图片描述
选择文件,点击提交后会带着文件访问http://localhost:8083/backend-product/product/manage/upload接口,并返回json数据
在这里插入图片描述

包括状态和 uri 以及 url。
在这里插入图片描述

然后本地文件夹保存上传的图片,表示图片上传成功!!!

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值