springboot实现单和多⽂件上传
springMVC对⽂件上传做了简化,springboot对此做了更进⼀步的简化。
java中的⽂件上传⼀共涉及两个组件,1.ComminsMultipartResolver 2.StandardServletMultipartResolver,其中ComminsMultipartResolver 使⽤commons-fileupload来处理multipart请求,⽽StandardServletMultipartResolver则是基于Servlet3.0来处理multipart请求,Tomcat7.0开始就⽀持Servlet3.0了,⽽spring boot 2.0.4内嵌的Tomcat为Tomcat8.5.32,
因此说⽩了就是使⽤springboot上传⽂件可以做到零配置,。
单⽂件上传
⾸先创建springboot项⽬并添加spring-boot-starter-web依赖
在resources⽬录下的templates⽬录创建upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--是actiob不是about,本⼈因为这个⼩问题研究了⼩半天-->
<!--上传接⼝是main/upload,注意使⽤post提交,enctype是multipart/form-data-->
<form action="main/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" value="选择⽂件" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
因为是在templates⽬录下创建的.html⽤户是不能直接访问的,我们通过下⾯代码访问
@GetMapping
public String upload() {
return "upload";
}
ller;
ity.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/main")
public class main {
//跳转到upload.html页⾯
@GetMapping
public String upload() {
return "upload";
}
//声明时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String update(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req) {
String realPath = Session().getServletContext().getRealPath("/uploadFile/");
String format = sdf.format(new Date());
File folder = new File(realPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
String oldName = OriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
//上传主要是transferTo⽅法
String filePath = Scheme() + "://" + ServerName() + ":" + ServletPath() + "/uploadFile/" + format + newName; return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
当然如果开发者需要对图⽚上传的细节进⾏配置,也是允许的,下⾯代码是我通过.yml配置的
spring:
servlet:
multipart:
enabled: true #表⽰⼗分开启⽂件上传,默认为true
file-size-threshold: 0 #⽂件写⼊磁盘的值,默认为0
resolve-lazily: false #是否延迟解析,默认为false
location: E://temp #表⽰⽂件临时保存位置
max-file-size: 1MB #上传单个⽂件最⼤⼤⼩,默认为1MB
max-request-size: 10MB #多⽂件上传总⼤⼩,默认为10MB
多⽂件上传
前端代码
在原本的代码中添加multiple表⽰⽀持选择多个⽂件
<input type="file" name="file" value="选择⽂件" multiple>
java修改html文件修改控制器:代码
修改接收的值就可以了,将其修改为数组,后⾯遍历数组拿到⽂件就可以了
⽂件下载
前端创建HTML
<a href="download">下载</a>
创建File_Download 控制类
ller;
import java.io.*;
import java.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class File_Download {
//实现Spring Boot 的⽂件下载功能,映射⽹址为/download
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
// 获取指定⽬录下的第⼀个⽂件
File scFileDir = new File("E://music");
File TrxFiles[] = scFileDir.listFiles();
System.out.println(TrxFiles[0]);
//下载的⽂件名
String fileName = TrxFiles[0].getName();
// 如果⽂件名不为空,则进⾏下载
if (fileName != null) {
//设置⽂件路径
String realPath = "E://music/";
File file = new File(realPath, fileName);
// 如果⽂件名存在,则进⾏下载
if (ists()) {
// 配置⽂件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载⽂件能正常显⽰中⽂
response.setHeader("Content-Disposition", "attachment;filename=" + de(fileName, "UTF-8"));
// 实现⽂件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = OutputStream();
int i = ad(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = ad(buffer);
}
System.out.println("Download the song successfully!");
}
catch (Exception e) {
System.out.println("Download the song failed!");
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论