SpringBoot文件上传

SpringBoot文件上传:

  • 文件上传和下载都是一件难题,今天我们的目的就是攻克这个难题
开始正题:
  • 首先创建一个SpringBoot项目,导入thmeleaf模板引擎和Web
  • Service层代码:
package com.zhang.upload_demo01.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadService {
    /*
    * MultipartFile 这个对象是SpringMVC/文件上传的一个接受的类
    * 它的底层会自动去和httpServletRequest request中的request.getInputStream()融合
    * 从而达到文件上传的效果
    *
    * 文件上传的底层原理就是:request.getInputStream()
    * @param MultipartFile
    * */
    @Value("${file.uploadPath}")
    private String uploadPath;
    public String uploadImag(MultipartFile multipartFile,String dir){
        // 1:指定文件上传目录

        try {
            // 2:保证文件名的唯一,截取文件名后缀
            String originalFilename = multipartFile.getOriginalFilename(); //获取文件 例如:aaa.jpg
            //截取文件名后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")); // .jpg
            //生成唯一文件名
            String newFile = UUID.randomUUID().toString()+substring; // 拼接成为 dadesbawe-d5aa64.jpg
            //指定上传目录--->时间目录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String format = sdf.format(new Date()); //2022-02-16 日期目录

            //String serverPath = "E://temp/";
            String serverPath = uploadPath;
            File targetFile = new File(serverPath+dir,format); // E://temp/${dir}/2022/02/16
            if (!targetFile.exists()){
                targetFile.mkdirs();
            }
            // 3:将文件上传到指定目录
            File targetFileName = new File(targetFile,newFile);
            //最终目录: E://temp/${dir}//2022/02/16/dadesbawe-d5aa64.jpg

            multipartFile.transferTo(targetFileName);
            //将用户选择的aaa.jpg 上传到E://temp/${dir}//2022/02/16/dadesbawe-d5aa64.jpg
            return dir+"/"+format+"/"+newFile;
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        }
    }
}
  • 使用这个也可以 放回的信息更加详细
package com.zhang.upload_demo02.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UploadService {
    @Value("${file.uploadLocation}")
    private String uploadLocation;

    public Map<String,Object> upload(MultipartFile multipartFile, String dir){
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String offlater = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFile = UUID.randomUUID().toString() + offlater;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String timeFile = sdf.format(new Date());
            String serverPath = uploadLocation;
            // F://temp/images    // F://temp/images/
            File targetPath = new File(serverPath+dir,timeFile);
            if (!targetPath.exists()){
                targetPath.mkdirs();
            }
            File targetFile = new File(targetPath,newFile);
            multipartFile.transferTo(targetFile);
            String filename = dir+"/"+timeFile + "/" + newFile;

            Map<String,Object> map = new HashMap<>();
            map.put("url","http://localhost:8777"+"/img/"+filename);
            map.put("name",newFile);
            map.put("suffix",offlater);
            map.put("size",multipartFile.getSize());
            map.put("rpath",dir+"/"+timeFile + "/" + newFile);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
  • Controller层代码:
package com.zhang.upload_demo01.controller;

import com.zhang.upload_demo01.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @RequestMapping("/")
    public String toIndex(){
        return "upload";  //首页定位用的
    }
    @PostMapping("/upload/file")
    @ResponseBody
    public String upload(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request){
        if (multipartFile.isEmpty()){
            return "文件有误";
        }
        //文件大小
        long size = multipartFile.getSize();
        //文件真实名称
        String originalFilename = multipartFile.getOriginalFilename();
        //文件类型
        String contentType = multipartFile.getContentType();

        String dir = request.getParameter("dir");
        return uploadService.uploadImag(multipartFile,dir);
    }
}

  • HTML层代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload/file" method="post" enctype="multipart/form-data">
        <input name="dir" value="images">
        <input name="file" type="file">
        <input type="submit" value="文件上传">
    </form>
</body>
</html>
  • application.yaml 和 application-dev.yaml 一定要做环境隔离
#服务配置
file:
  staticPath: /upload/**
  uploadPath: E:/temp/


server:
  port: 8080
spring:
  profiles:
    active: dev
  • OSS文件上传 需要去阿里云申请一下OSS服务
package com.zhang.upload_demo02.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssUploadService {
    public String uploadfile(MultipartFile multipartFile,String dir){
                // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。关于其他Region对应的Endpoint信息,请参见访问域名和数据中心。
                String endpoint = "oss-cn-beijing.aliyuncs.com";
                // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
                //LTAI5t73fB85acU8TfeE9io2
                //6Tg0RyOfeyVTebD209Y45O13Bwaoz8
                String accessKeyId = "***";//安全密钥用户名
                String accessKeySecret = "***"; //安全密码
                // 填写Bucket名称,例如examplebucket。
                String bucketName = "zitbookings";

                // 创建OSSClient实例。

                OSS ossClient =null;
                try {
                    ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

                    // 1.获取文件上传流
                    InputStream inputStream = multipartFile.getInputStream();
                    // 2.构建日期目录
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    String dataPath = sdf.format(new Date());
                    // 4.获取文件真实名字 并重构
                    String originalFilename = multipartFile.getOriginalFilename();
                    String filename = UUID.randomUUID().toString();
                    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                    String newName = filename + suffix;

                    String fileUrl = dir +"/"+ dataPath + newName;

                    // 5.文件上传到阿里云云服务器
                    ossClient.putObject(bucketName, fileUrl, inputStream);

                    return "http://" +  bucketName + "." + endpoint + "/" + fileUrl;
                } catch (OSSException oe) {
                    System.out.println("Caught an OSSException, which means your request made it to OSS, "
                            + "but was rejected with an error response for some reason.");
                    System.out.println("Error Message:" + oe.getErrorMessage());
                    System.out.println("Error Code:" + oe.getErrorCode());
                    System.out.println("Request ID:" + oe.getRequestId());
                    System.out.println("Host ID:" + oe.getHostId());
                    return "fail";
                } catch (ClientException ce) {
                    System.out.println("Caught an ClientException, which means the client encountered "
                            + "a serious internal problem while trying to communicate with OSS, "
                            + "such as not being able to access the network.");
                    System.out.println("Error Message:" + ce.getMessage());
                    return "fail";
                } catch (IOException e) {
                    e.printStackTrace();
                    return "fail";
                } finally {
                    if (ossClient != null) {
                        ossClient.shutdown();
                    }
                }

    }
}
  • 当然也可以集成一些文本编辑器:WangEditor和WebUpload 这个两个都可以 仁者见仁
  • WangEditor
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="div1">
    <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>

<!-- 引入 wangEditor.min.js -->
<script src="/editor/wangEditor.min.js"></script>
<script type="text/javascript">
    const E = window.wangEditor;
    const editor = new E('#div1')
    // 或者 const editor = new E( document.getElementById('div1') )
    editor.config.uploadImgServer = '/upload/Oss';
    editor.config.uploadFileName = 'file';
    editor.config.uploadImgParams = {dir: "bbs"};
    editor.config.uploadImgHooks = {
        // 上传图片之前
        before: function(xhr) {
           return true;
        },
        // 图片上传并返回了结果,图片插入已成功
        success: function(xhr) {
            console.log('success', xhr)
        },
        // 图片上传并返回了结果,但图片插入时出错了
        fail: function(xhr, editor, resData) {
            console.log('fail', resData)
        },
        // 上传图片出错,一般为 http 请求的错误
        error: function(xhr, editor, resData) {
            console.log('error', xhr, resData)
        },
        // 上传图片超时
        timeout: function(xhr) {
            console.log('timeout')
        },
        // 图片上传并返回了结果,想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
        customInsert: function(insertImgFn, result) {
            console.log("你上传的的地址是:",result);
            // result 即服务端返回的接口
            console.log('customInsert', result);
            // insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
            insertImgFn(result.url);
        }
    }
    editor.create()
</script>
</body>
</html>
  • WebUpload
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="/upload/webuploader.css" />
    <script type="text/javascript" src="/upload/webuploader.js"></script>
    <script type="text/javascript" src="/upload/jquery-3.6.0.js"></script>
</head>
<body>
<!--dom结构部分-->
<div id="uploader-demo">
    <!--用来存放item-->
    <div id="fileList" class="uploader-list"></div>
    <div id="filePicker">选择图片</div>
</div>



<script>
    // 初始化Web Uploader
    var uploader = WebUploader.create({

        // 选完文件后,是否自动上传。
        auto: true,

        // swf文件路径
        swf: '/upload/Uploader.swf',

        // 文件接收服务端。
        server: '/upload/Oss',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: '#filePicker',

        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        }
    });
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot中实现文件上传非常简单。首先,你需要在项目的依赖中添加spring-boot-starter-web。然后,你可以通过配置文件来对文件上传进行一些基本的配置。例如,你可以设置是否开启文件上传支持、文件写入磁盘的阈值、上传文件的临时保存位置、上传的单个文件的最大大小以及多文件上传时文件的总大小等。\[1\] 对于单文件上传,你可以创建一个HTML表单,使用enctype="multipart/form-data"来指定表单的编码类型,并使用<input type="file">来选择文件。然后,你可以在后端编写一个处理文件上传的接口,通过@RequestParam注解来获取上传的文件。\[2\] 对于多文件上传,你可以创建一个HTML表单,使用相同的方式来选择多个文件。然后,你可以在后端编写一个处理多文件上传的接口,通过@RequestParam注解来获取上传的文件列表。\[2\] 在Spring Boot中,如果你没有提供MultipartResolver,那么默认采用的MultipartResolver就是StandardServletMultipartResolver。因此,你甚至可以实现零配置的文件上传。\[3\] 总结起来,Spring Boot提供了简单而强大的功能来实现文件上传,你只需要添加依赖、进行一些基本的配置,然后在后端编写相应的接口即可实现文件上传功能。 #### 引用[.reference_title] - *1* *2* *3* [SpringBoot文件上传](https://blog.csdn.net/qq_43581790/article/details/123811775)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秃头路上的小强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值