[SpringBoot]文件上传实现步骤

以下是一个简易版完整案例详细步骤:

用来熟悉文件上传操作

创建工程:
https://blog.csdn.net/YJH000_/article/details/130305008?spm=1001.2014.3001.5501 
 

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.9/theme-chalk/index.css">
</head>
<body>
<div id="app">

</div>
</body>
<!-- import axios -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<!-- import Vue before Element -->
<script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<script>
 let v = new Vue({
    el: '#app',
    data: function() {
      return {

      }
    },
   methods:{

   }
  })
</script>
</html>

打开element官网
Element - The world's most popular Vue UI frameworkElement,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库https://element.eleme.cn/#/zh-CN/component/upload
 

 展开代码后:

 

 

 发微博插入时间代码:

 insert(){
       if(v.weibo.url==""){
         alert("请选择上传的图片")
         return;
       }
       //发出新增微博的异步请求
       axios.post("/insert",v.weibo).then(function () {
         location.href="/";//返回首页
       })
     },

 
成功是接收客户端响应时间的代码:

  handleSuccess(response,file,fileList){
       //上传成功后把服务器响应的图片路径赋值给微博对象
       v.weibo.url=response;
       //此方法是上传组件内部调用的方法,response代表服务器响应的数据和axios的response不一样,不需要.data
       //file代表当前上传完成的文件对象
       //fileList代表的是上传完成的所有文件对象  例如先上传a file是a fileList是a 在上传b file是b fileList是a和b
        alert(response);
     },

 

 
删除事件的代码:

   handleRemove(file, fileList) {
       //因为图片被删除了 所以weibo对象里面的图片路径应该被清除
       v.weibo.url="";
       console.log(file, fileList);
       //发出异步的删除请求 file.response代表服务器上传成功时响应的文件路径
       axios.post("/remove?url="+file.response).then(function () {
         console.log("删除完成!");
       })
     },

 文件上传代码:

  /*文本文件保存在数据库中,图片保存在磁盘中,在数据库中保存文本数据的同时,保存图片的
    * 路径以此建立联系*/


    //上传文件有默认大小的限制,默认为1兆,超过会报错需要在application里面去配置更改
    //用MultipartFile对象接收,并且参数名要和页面设置的name参数名称要一致
    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        //得到文件的原始文件名
        String fileName=picFile.getOriginalFilename();
        System.out.println(fileName);
        //为了防止图片的名字相同导致的覆盖,需要设置唯一性名字,做以下操作
        //得到文件名后缀   最后一个点的位置截取到最后即a.jpg得到.jpg
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        //后缀得到后,得到唯一文件名   UUID.randomUUID()获得一个字符串类型的唯一标识符
        fileName= UUID.randomUUID()+suffix;
        System.out.println(fileName);

        //保存到磁盘中
        //准备文件夹路径
        String dirPath="d:/files";
        //准备一个和日期相关的路径
        //yyyy年 MM月 dd日 意思就是我准备一个这个格式,给我生成一个这个格式的年月日
        SimpleDateFormat f=new SimpleDateFormat("/yyyy/MM/dd/");
        //new Date()得到的是当前的系统时间
        String datePath=f.format(new Date());//java.util中的Date

        //创建文件夹
        //d:/files/yyyy/MM/dd/
        File dirFile=new File(dirPath+datePath);
        if(!dirFile.exists()){//这个路径的文件夹如果不存在,则创建
            dirFile.mkdirs();
        }

        //把接收到的文件保存到上面的文件夹下面   d:/files/yyyy/MM/dd/xxxx.jpg
        picFile.transferTo(new File(dirPath+datePath+fileName));

        ///yyyy/MM/dd/xxxx.jpg返回这个路径给remove发请求当参数用
        return datePath+fileName;
    }

文件删除代码:
 

   @RequestMapping("/remove")
    public void remove(String url){
        System.out.println("url = " + url);
        File f=new File("d:/files"+url);
        f.delete();
    }

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对您的问题,下面是SpringBoot实现文件上传下载的步骤: 1.引入相关依赖 ```xml <!-- 文件上传下载依赖 --> <!-- 文件上传支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 文件上传下载支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- 文件上传下载支持 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-logging-juli</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> ``` 2.编写文件上传接口 ```java @RestController @RequestMapping("/file") public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { return "文件为空"; } // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 设置文件存储路径 String filePath = "D:/upload/"; // 重新生成文件名 fileName = UUID.randomUUID() + suffixName; // 创建文件路径 File dest = new File(filePath + fileName); // 存储文件 file.transferTo(dest); return "上传成功"; } } ``` 3.编写文件下载接口 ```java @RestController @RequestMapping("/file") public class FileController { @GetMapping("/download") public ResponseEntity<byte[]> downloadFile() throws IOException { // 设置文件路径 String filePath = "D:/upload/"; // 设置文件名 String fileName = "test.txt"; // 获取文件对象 File file = new File(filePath + fileName); // 创建字节输入流 InputStream in = new FileInputStream(file); // 创建字节数组 byte[] bytes = new byte[in.available()]; // 将字节输入流读入字节数组 in.read(bytes); // 创建HttpHeaders对象 HttpHeaders headers = new HttpHeaders(); // 设置下载文件名 headers.setContentDispositionFormData("attachment", fileName); // 设置响应类型 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 封装响应结果 ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK); return responseEntity; } } ``` 以上就是SpringBoot实现文件上传下载的步骤。如果您有其他问题需要咨询,欢迎继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值