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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM