栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

springboot实现上传文件

Java 更新时间:发布时间: 百科书网 趣学号
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;


@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
    
    @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
@Component
@Configuration
@Slf4j
public class FileUtil {

    private static String property = System.getProperty("user.dir");
    
    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 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;
    }

    
    public static List multiFileUpload(List 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 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;
    }

    
    public static ResponseEntity 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 response = new ResponseEntity(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访问

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/986560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号