SpringBoot实现文件上传功能_第1页
SpringBoot实现文件上传功能_第2页
SpringBoot实现文件上传功能_第3页
SpringBoot实现文件上传功能_第4页
SpringBoot实现文件上传功能_第5页
已阅读5页,还剩2页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第SpringBoot实现文件上传功能经典的文件上传

服务器处理上传文件一般都是先在请求中读取文件信息,然后改变名称保存在服务器的临时路径下,最后保存到服务器磁盘中。本次以thymeleaf搭建demo,因此需要引入thymeleaf依赖库。

dependency

groupIdorg.springframework.boot/groupId

artifactIdspring-boot-starter-thymeleaf/artifactId

version2.5.5/version

/dependency

如果使用的是gradle构建的项目,需要修改build.gradle文件:

compile'org.springframework.boot:spring-boot-starter-thymeleaf:2.5.5'

新建一个Action类负责处理上传的文件:

@RestController

@RequestMapping("/upload/*")

publicclassUploadAction{

@PostMapping("/file")

publicObjectuploadHandler(HttpServletRequestrequest,Stringtitle,MultipartFilefile){

MapString,ObjectresultMap=newLinkedHashMap();

resultMap.put("title",title);

resultMap.put("fileName",file.getName());//文件名

resultMap.put("originalFilename",file.getOriginalFilename());//原始名称

resultMap.put("content-type",file.getContentType());//文件类型

resultMap.put("fileSize",file.getSize()/1024+"K");//文件大小

try{

//保存文件

StringuploadedFilePath=saveFile(request,file.getInputStream(),file.getOriginalFilename()

.substring(file.getOriginalFilename().lastIndexOf(".")+1));

resultMap.put("uploadedFilePath",uploadedFilePath);//文件大小

}catch(IOExceptione){

System.err.println("error-path:/upload/file,message:"+e.getMessage());

returnresultMap;

*保存上传的文件到本地服务器

*@paramrequestHttpServletRequest

*@paraminput输入流

*@paramext文件扩展名

*@return文件路径

*@throwsIOException

publicStringsaveFile(HttpServletRequestrequest,InputStreaminput,Stringext)throwsIOException{

StringrealPath=request.getServletContext().getRealPath("/upload/file/");//取得服务器真实路径

Filefile=newFile(realPath);

if(!file.getParentFile().exists()){//目录不存在

file.mkdirs();//创建多级目录

StringfilePath=realPath+UUID.randomUUID()+"."+ext;

//取的文件输出流

OutputStreamout=newFileOutputStream(filePath);

byte[]data=newbyte[2048];//缓冲数组2KB

intlen=0;//读取字节长度

while((len=input.read(data))!=-1){

out.write(data,0,len);//文件写入磁盘

if(input!=null){

input.close();

out.close();

returnfilePath;

}

在resources目录下新建templates文件夹,在里面创建index.html文件作为项目首页展示。

!doctypeHTML

htmlxmlns:th=""

head

title文件上传测试/title

metacharset="UTF-8"/

/head

body

formaction="/upload/file"method="post"enctype="multipart/form-data"

span标题:/span

inputtype="text"name="title"/br

span文件:/span

inputtype="file"name="file"/br

inputtype="submit"value="上传"/

/form

/body

/html

启动项目,直接访问:http://localhost:8080/将进入index.html页面。

点击上传按钮,文件将被保存到服务器磁盘中:

SpringBoot对上传文件处理的简化

SpringBoot对FileUpload组件进行了整合,在文件保存的时候可以避免直接操作IO流,通过配置文件的方式指定文件上传的限制参数。修改application.yml文件:

server:

port:8080

spring:

servlet:

multipart:

enabled:true#启用文件上传

max-file-size:1MB#单文件上传最大限制

max-request-size:10MB#文件上传最大值

file-size-threshold:10KB#上传文件达到多大时写入磁盘

location:/#临时文件存储位置

修改UploadAction,使用MultipartFile类的transferTo方法保存上传文件。

@RestController

@RequestMapping("/upload/*")

publicclassUploadAction{

@PostMapping("/file")

publicObjectuploadHandler(HttpServletRequestrequest,Stringtitle,MultipartFilefile){

MapString,ObjectresultMap=newLinkedHashMap();

resultMap.put("title",title);

resultMap.put("fileName",file.getName());//文件名

resultMap.put("originalFilename",file.getOriginalFilename());//原始名称

resultMap.put("content-type",file.getContentType());//文件类型

resultMap.put("fileSize",file.getSize()/1024+"K");//文件大小

try{

//保存文件

Stringetc=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);

StringserverPath=request.getScheme()+"://"+request.getServerName()

+":"+request.getServerPort()+request.getContextPath()+"/file/upload/";

StringfileName=UUID.randomUUID()+"."+etc;

resultMap.put("filePath",serverPath+fileName);//文件地址(服务器访问地址)

//文件保存再真实路径下

FilesaveFile=newFile(request.getServletContext().getRealPath("/file/upload/")+fileName);

if(!saveFile.getParentFile().exists()){//目录不存在,创建目录

saveFile.mkdirs();

file.transferTo(saveFile);//保存上传文件

}catch(IOExceptione){

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论