概述
常用的springboot+scala实现的webservice上传下载,
maven配置文件采用常规配置,见springboot+scala配置
后端代码
FileController.scala
package org.tashaxing.controller
import java.io._
import org.springframework.web.bind.annotation._
import org.springframework.core.io.{InputStreamResource, Resource}
import org.springframework.http.ResponseEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.multipart.MultipartFile
@RestController
@RequestMapping(Array("/api"))
class FileController
{
@PostMapping(Array("/file/upload/{myparam}"))
def uploadFile(@PathVariable(value = "myparam") myparam: String, // extra param submitted
@RequestBody file: MultipartFile): Boolean =
{
if (file.isEmpty)
return false
val filename = file.getOriginalFilename
val suffix = filename.substring(filename.lastIndexOf('.'))
// save to directory
// here do sth to handle the file record, maybe insert record to database
val save_dir = "D:/file" // absolute and relative path are both OK
val save_file = new File(save_dir + '/' + filename) // we can customize the filename, make sure the suffix is right
file.transferTo(save_file) // save to file system
return true
}
@PostMapping(Array("/file/delete/{filename}"))
def deleteReceipt(@PathVariable(value = "filename") filename: String): Boolean =
{
// first maybe delete record from database
// delete from file system
val file_dir = "D:/file" // absolute and relative path are both OK
val file = new File(file_dir + '/' + filename)
if (file.exists())
file.delete()
return true
}
@GetMapping(Array("/file/download/{filename}"))
def downloadReceipt(@PathVariable(value = "filename") filename: String): ResponseEntity[Resource] =
{
// just support download pdf for this demo
val headers = new HttpHeaders
headers.setContentType(MediaType.parseMediaType("application/pdf")) // maybe other format: application/png
val file = new File(FbConfig.file_root + '/' + filename)
val resource = new InputStreamResource(new FileInputStream(file))
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource)
}
}
前端代码
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit" />
</form>
<a href="/download">下载</a>
</html>
这样就简单实现了一个上传下载功能,需要注意的是
- 前端的input空间里面name要和后端的upload函数里面的参数对应,如:“file”
- 前端可以用react之类的框架包装,但是写法基本一致,上传用表单,下载用href链接
- 如果要支持多种文件格式,后端基本不用改,只要在下载的函数里面改一下文件格式
- 需要在springboot的配置文件里面指定上传下载的文件大小上限
最后
以上就是痴情超短裙为你收集整理的sprintboot+scala文件上传下载的全部内容,希望文章能够帮你解决sprintboot+scala文件上传下载所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复