zoukankan      html  css  js  c++  java
  • SpringBoot 上传文件功能

    注意事项:

       springboot默认有以下文件配置要求, 可以自行在配置文件里面修改


    spring:
    servlet:
    multipart:
    enabled: true #是否处理上传
    max-file-size: 1MB #允许最大的单个上传大小,单位可以是kb
    max-request-size: 10MB #允许最大请求大小
    package com.example.demo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.util.UUID;
    
    @Controller
    public class FileUploadController {
    
    
        /**
         * 因为最终项目会打成jar包,所以这个的路径不能是jar包里面的路径
         * 可以使用其他路径,比如上传到F盘下的upload文件夹下 写成:F:/upload/
         */
        private String fileUploadPath;
    
        /**
         * 文件上传,具体逻辑可以自行完善
         *
         * @param file 前端表单的name名
         * @return w
         */
        @PostMapping("/upload")
        @ResponseBody
        public String upload(MultipartFile file) {
    
            if (file.isEmpty()) {
                //文件空了
                return null;
            }
    
            //文件扩展名
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("/"));
    
            //使用UUID生成文件名称
            String fileName = UUID.randomUUID().toString() + extName;
    
            //文件上传的全路径
            String filePath = fileUploadPath + fileName;
    
            File toFile=new File(filePath);
    
            if (!toFile.getParentFile().exists()){
                //文件夹不存在,先创建文件夹
                toFile.getParentFile().mkdirs();
            }
            try {
                //进行文件复制上传
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile));
            } catch (Exception e) {
                //上传失败
                e.printStackTrace();
            }
            //返回文件所在绝对路径
            return filePath;
    
        }
    
    }
  • 相关阅读:
    解决Mac下GDB提示签名错误
    hdu 5015 大数量反复类似操作问题/ 矩阵高速幂
    数据运营报表系统思考 一二
    NGUI 3.5教程(二)Label 标签 (Hello world)、多行文本
    STL 源代码剖析 算法 stl_algo.h -- equal_range
    java字符操作获取汉字的拼音以及其它经常使用工具
    SRAM,SDRAM,网卡
    java.lang.NoClassDefFoundError: ognl/PropertyAccessor解决的方法
    纯手工定制西服怎么鉴别
    缝份_百度百科
  • 原文地址:https://www.cnblogs.com/pxblog/p/12969177.html
Copyright © 2011-2022 走看看