java实现文件上传到指定目录

本文介绍如何使用Spring框架中的MultipartFile进行文件上传操作,包括配置、实现上传至项目路径或磁盘的方法,以及判断文件类型的实用代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

最近有用到文件上传,所以了解了一下Spring中的MultipartFile,然后进行一个简单的记录

首先要在yml文件中进行配置
在这里插入图片描述
我们根据业务的不同,有可能是需要上传到项目路径下,也有可能是上传到系统磁盘中,我这边是利用接口的方式进行测试,还没来得及封装为工具类,大家先凑合看,希望为大家提供一些帮助~~

package com.komlin.project.api.controller;

import com.komlin.common.utils.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Description:接口测试
 * date: 2020/8/19 9:42
 *
 * @author mt
 * @since JDK 1.8
 */

@Api(tags = "接口测试")
@RestController
@Slf4j
@RequestMapping("api/mtTest")
public class ApiMtTestController {

    //图片存放的系统磁盘路径
    private final static String SAVE_PATH = "C:\\pic\\";

    //项目路径
    private final static String FILE_SAVE_PREFIX = "static/sltimage";

    /**
     * 将文件放到指定目录下
     * @param type 类型
     * @return
     */
    private static File getFile(int type) {
        File file = null;
        String filePath = null;
        if (Objects.equals(type,1)) {
            //上传到项目路径下
            filePath = new String("src/main/resources/" + FILE_SAVE_PREFIX);
            file = new File(filePath);
        } else if (Objects.equals(type,2)) {
            //上传到磁盘
            filePath = new String(SAVE_PATH);
            file = new File(filePath);
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 判断文件是否为图片
     *
     * @param type
     * @return
     */
    private static boolean isImg(String type) {
        if (StringUtils.isNotEmpty(type)) {
            if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 上传文件到指定目录
     * @param file 文件
     * @param pathType  路径类型 1 上传到项目路径下 2 上传到磁盘
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/save")
    public String fileTest(@RequestParam("photo") MultipartFile file, Integer pathType,HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        //文件大小
        long size = file.getSize();
        //文件的byte大小
        byte[] bytes = file.getBytes();
        //文件原名称
        String fileName = file.getOriginalFilename();
        //文件类型
        String type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;
        if (type == null) {
            return "文件类型为空";
        }
        // 判断文件类型是否为图片
        if (isImg(type)) {
            //项目在容器中实际发布运行的根路径
            String realPath = request.getSession().getServletContext().getRealPath("/");
            //自定义的文件名称,避免文件名重复
            String trueFileName = "komlin_pic_" + String.valueOf(System.currentTimeMillis()) + "." + type;
            File fileDir = getFile(pathType);
            File newFile = new File(fileDir.getAbsolutePath() + "/" + trueFileName);
            file.transferTo(newFile);
            return "文件成功上传到指定目录下";
        }
        return "不是图片类型";
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值