springboot实现上传文件

springboot实现上传文件

一、项目目录

项目目录结构

一、实现

1.WebMvcConfig.java

package com.hhu.gq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * @description: 图片绝对地址与虚拟地址映射
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //本地目录
        String property = System.getProperty("user.dir");
        File file3 = new File(property);
        String filePath = file3.getParent()+File.separator+"files"+File.separator;
        log.info(filePath);
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+filePath);
    }

}

2.FileUtil.java

package com.hhu.gq.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * @description: 文件处理
 */
@Component
@Configuration
@Slf4j
public class FileUtil {

    private static String property = System.getProperty("user.dir");
    /**
     * 单文件上传文件
     *
     * @param multipartFile
     * @param folder
     * @return
     */
    public static String fileUpLoad(MultipartFile multipartFile, String folder) {
        /* 获取项目路径 */
        File file3 = new File(property);
        String filePath = file3.getParent() + File.separator + "files" + File.separator;
        if (folder != null) {
            filePath += folder + File.separator;
        }
        log.info("需要插入的文件夹为:{}", filePath);
        // 自定义的文件名称
        String trueFileName = UUID.randomUUID().toString();
        // 文件原名称
        String fileName = multipartFile.getOriginalFilename();
        // 文件类型
        String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())
                : null;
        // 设置存放图片文件的路径
        String path = null == type ? filePath + File.separator + trueFileName
                : filePath + File.separator + trueFileName + "." + type;
        File file2 = new File(filePath);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        // 转存文件到指定的路径
        try {
            multipartFile.transferTo(new File(path));
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("path", null == type ? trueFileName : trueFileName + "." + type);
            log.info(resultMap.toString());
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        log.info("文件夹位置:" + filePath + folder + File.separator);
        return folder + File.separator + trueFileName + "." + type;
    }

    /**
     * 多文件上传文件
     *
     * @param folder 想要存储的文件夹
     * @param files  文件列表:List<MultipartFile>
     * @return 存储的文件的列表
     */
    public static List<String> multiFileUpload(List<MultipartFile> files, String folder) {
        /* 获取项目路径 */

        File file3 = new File(property);
        String filePath = file3.getParent() + File.separator + "files" + File.separator;
        if (folder != null) {
            filePath += folder + File.separator;
        }
        log.info("需要插入的文件夹为:{}", filePath);
        MultipartFile multipartFile = null;
        BufferedOutputStream stream = null;
        List<String> locationOfStoredFiles = new ArrayList<>();
        for (int i = 0; i < files.size(); ++i) {
            multipartFile = files.get(i);
            // 自定义的文件名称
            String trueFileName = UUID.randomUUID().toString();
            // 文件原名称
            String fileName = multipartFile.getOriginalFilename();
            // 文件类型
            String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())
                    : null;
            // 设置存放图片文件的路径
            String path = null == type ? filePath + File.separator + trueFileName
                    : filePath + File.separator + trueFileName + "." + type;
            File file2 = new File(filePath);
            if (!file2.exists()) {
                file2.mkdirs();
            }
            // 转存文件到指定的路径
            if (!multipartFile.isEmpty()) {
                try {
                    byte[] bytes = multipartFile.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(path)));
                    stream.write(bytes);
                    stream.close();
                    locationOfStoredFiles.add(folder + File.separator +trueFileName+'.'+type);
                } catch (IllegalStateException | IOException e) {
                    stream = null;
                    log.info("第 " + i + " 个文件上传失败 ==> " + e.getMessage());
                }
            } else {
                log.info("第 " + i + " 个文件上传失败因为文件为空");
            }
        }
        return locationOfStoredFiles;
    }

    /**
     * 下载访问方式:http://localhost:8090/image/test/e4c0973e-0462-428d-93f5-b036864835c9.JPG
     *
     * @param folder
     * @param fileName
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> downloadFile(String folder, String fileName) throws IOException {
        File file3 = new File(property);
        String filePath = file3.getParent() + File.separator + "files" + File.separator;
//        String filePath = property.getParent() + File.separator + "files" + File.separator;
        if (folder != null) {
            filePath += (folder + File.separator);
        }
        byte[] body = null;
        if (fileName != null) {
            File file = new File(filePath + fileName);
            if (file.exists()) {
                // 将该文件加入到输入流之中
                InputStream in = new FileInputStream(file);

                // 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
                body = new byte[in.available()];
                try {
                    // 读入到输入流里面
                    in.read(body);
                    // 防止中文乱码
                    fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        HttpHeaders headers = new HttpHeaders();// 设置响应头
        headers.add("Content-Disposition", "attachment;filename=" + fileName);
        HttpStatus statusCode = HttpStatus.OK;// 设置响应码
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
}

3.controller.java

package com.gq.controller;

import com.gq.service.DemoService;
import com.gq.utils.FileUtil;
import com.gq.utils.ResponseResult.Result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/demo")
@CrossOrigin(origins = "*")
@ResponseResult
public class DemoController {
    @PostMapping(value = "add_image")
    public String addVehicle(HttpServletRequest httpServletRequest){
        // 上传图片
        MultipartFile image = ((MultipartHttpServletRequest) httpServletRequest).getFile("image");
        String url = "";
        if (image != null){
            //图片不为空则存储磁盘并获取图片地址
            url = FileUtil.fileUpLoad(image, "fav");
        }
        System.out.println(url);
        return url;
    }
}

二、测试结果

1.前端请求

前端请求

2.后台打印

后台打印

3.本地磁盘

本地磁盘

4.url访问

url访问

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值