首页 > 其他分享 >SpringBoot实现简单文件上传功能

SpringBoot实现简单文件上传功能

时间:2023-11-21 16:11:26浏览次数:29  
标签:文件 SpringBoot 上传 upload springframework file import data

通过 SpringBoot 实现了表单下的文件上传,前后端分离情况下的文件上传。本案例不连接数据库,只做基本的文件上传操作。

在 SpringBoot 中不需要额外导入其他依赖,正常引入即可。

后端 controller 的写法

package com.dailyblue.java.controller;    import org.springframework.util.ResourceUtils; 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.RestController; import org.springframework.web.multipart.MultipartFile;    import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException;    @RestController @RequestMapping("/upload") public class UploadController {        @PostMapping     public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {         // file:上传文件         // 获取到 images 的具体路径         // String realPath = request.getRealPath("images");         String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/images";         System.out.println("上传的文件地址是:" + realPath);         // 服务器中对应的位置         // 产生唯一的文件名称         String fileName = UUID.getUUid();         // 获取到文件后缀         String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));         File src = new File(realPath, fileName + fileType);         // 将file文件传递到src去         file.transferTo(src);         return "images/" + fileName + fileType;     } }

这里只做了简单的文件上传,没有限制文件类型。 

前端写法

这里分为两种写法,一种是常用的表单提交,另一种是当下较火的 Vue 上传方式。

表单写法

<form action="upload" method="post" enctype="multipart/form-data">     <input type="file" name="file"/>     <button>上传</button> </form>

Vue 写法

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <body> <div id="app">     <img :src="'http://localhost:8081/'+img" v-show="flag"/>     <input type="file" @change="changeImg"/>     <button @click="upload">Vue 上传</button> </div> </body> </html>   <script src="js/vue.min.js"></script> <script src="js/axios.min.js"></script> <script>     new Vue({         el: '#app',         data: {             file: null,             img: '',             flag: false         },         methods: {             changeImg(event) {                 this.file = event.target.files[0];             },             upload() {                 // 表单数据                 let data = new FormData();                 data.append('file', this.file);                 // 定义发送格式                 let type = {                     headers: {                         'Content-Type': 'multipart/form-data'                     }                 }                 axios.post('http://localhost:8081/upload', data, type)                     .then((response) => {                         this.img = response.data;                         this.flag = true;                     });             }         }     }); </script>

以上就是本文的全部内容。

 

参考文章:http://blog.ncmem.com/wordpress/2023/11/21/springboot%e5%ae%9e%e7%8e%b0%e7%ae%80%e5%8d%95%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%8a%9f%e8%83%bd/

欢迎入群一起讨论

 

 

标签:文件,SpringBoot,上传,upload,springframework,file,import,data
From: https://www.cnblogs.com/songsu/p/17846834.html

相关文章

  • springboot移动端授权登录请求接口说明
    使用系统内部演示代码,在附件下载方便统一管理用户方便在线用户监控一处编写、处处可用统一鉴权方式1.新增角色、用户组【若已分配可跳过】角色管理-新增专门用于移动等模块-不分配任何后台菜单【DZDS已有】2.新增、修改用户在业务模块添加、修改用户信息,需要同步到sys_user中......
  • springboot多环境配置
    转载自:www.javaman.cn前言在实际项目研发中,需要针对不同的运行环境,如开发环境、测试环境、生产环境等,每个运行环境的数据库...等配置都不相同,每次发布测试、更新生产都需要手动修改相关系统配置。这种方式特别麻烦,费时费力,而且出错概率大。SpringBoot为我们提供了更加简单方便的......
  • Linux文件权限
    4.1基本权限UGOU:owner,属主G:group,属组O:other,其他用户r:read(读),数字设定4w:write(写入),数字设定2x:execute(执行),数字设定14.1.1设置文件属性与权限chown:修改文件属主/属组chgrp:修改文件属组chmod:修改文件权限4.2基本权限ACLgetfacl:查看ACL权限setfacl:设置ACL权......
  • 基于vsftpd搭建项目文件服务器
    vsftpd是“verysecureFTPdaemon”的缩写,安全性是它的一个最大的特点。vsftpd是一个UNIX类操作系统上运行的服务器的名字,它可以运行在诸如Linux、BSD、Solaris、HP-UNIX等系统上面,是一个完全免费的、开放源代码的ftp服务器软件,支持很多其他的FTP服务器所不支持的特征。......
  • 【Python】geopandas 读取 shp/geojson 边界文件
    1.读取shp/geojson边界文件importgeopandasasgpdfile='media/abc.geojson'gdf=gpd.read_file(file)#将GeoDataFrame转换为GeoJSON字符串geojson=json.loads(gdf.to_json())features=geojson['features']2.获取边界文件的网格范围importgeopandas......
  • 【Python】pandas 读取 后向轨迹文件
    importpandasaspdfrompathlibimportPathdefbackwardtrace(file:str):ifnotPath(file).is_file():raiseValueError('Filedoesnotexist!')else:res=[]withopen(file)asf:line=f.readline......
  • 零代码编程:用ChatGPT根据视频标题来批量重命名字幕文件
    现在有很多视频文件:还有视频相对应的字幕文件:F:\儿童学习教育\Abadas.适合2岁以上.BBC儿童学习单词的动画\abadas字幕两者的文件标题不一样,现在要将字幕文件的标题全部根据视频文件来重命名。在chatGPT中输入提示词:你是一个Python编程专家,要完成一个根据视频标题来批量重命名字幕文......
  • file函数读写文件(txt)操作
    文件操作open()方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数格式:open(file_name[,accesss_mode][,buffering])1、file_name:文件路径,必传参数2、accesss_mode:打开文件的模式(只读(r),写入(w),追加(a)等,默认为只读(r))。非必传3、buffering:为0表示不会......
  • CPC只需要上传主色吗资质怎样才算资质通过?
    CPC-高频疑难解答CPC,即儿童产品证书(Children’sProductCertificate),它适用于所有以12岁及以下儿童为主要目标使用对象的产品,类似于质检报告证书,在通过相关检测、出具报告后同时发放的证书。有许多儿童产品需要一定的认证资质才可以出口,卖家要保证产品是符合所有美国本地适用的......
  • 读取超图数据文件中的图元数量并输出
    时不时有统计数据量的需求,本来都是挨个打开数来着,后来发现,其实就是sqlite3的数据库,干脆写个脚本得了。 <?php//本代码用于对超图数据文件中各个数据集的数量和类型进行统计//udb/udd格式中udd是数据文件,udbx直接是数据文件,应该选择这两类文件作为参数,附加到代码命令后/......