睿虎的博客

按照以下的步骤创建项目:

然后在 application.properties 文件中写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
spring.thymeleaf.prefix=classpath:/templates/
server.port=8010


spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB



spring.datasource.url=jdbc:mysql://127.0.0.1:3306/paper?characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=yourpassword



mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

最后创建相关目录:

下面是用SpringBoot完成文件下载的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Controller
@RequestMapping("/download")
public class DownloadController {

@ResponseBody
@RequestMapping("/download")
public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
String downloadFilePath="D:\\laiscdata";
File file = new File(downloadFilePath +'\\'+ fileName);
if(!file.exists()){
return "下载文件不存在";
}
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
System.out.println("程序错误:"+e);
return "下载失败";
}
return "下载成功";
}
}

测试:访问http://localhost:8088/download/download?fileName=1.zip

下面是用SpringBoot完成文件上传的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Controller
@RequestMapping("/upload")
public class UploadController {

@ResponseBody
@RequestMapping("/upload")
public String httpUpload(@RequestParam("files") MultipartFile files[]){
String uploadFilePath="D:\\laiscdata";
JSONObject object=new JSONObject();
for(int i=0;i<files.length;i++){
String fileName = files[i].getOriginalFilename(); // 文件名
File dest = new File(uploadFilePath +'\\'+ fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
files[i].transferTo(dest);
} catch (Exception e) {
System.out.println("程序错误:"+e);
object.put("success",2);
object.put("result","程序错误,请重新上传");
return object.toString();
}
}
object.put("success",1);
object.put("result","文件上传成功");
return object.toString();
}

}

上面的代码看起来有点多,其实就是一个上传的方法,首先通过 MultipartFile 接收文件。这里我用的是file[] 数组接收文件,这是为了兼容多文件上传的情况,如果只用file 接收,然后在接口上传多个文件的话,只会接收最后一个文件。这里大家注意一下。看自己的需求,我这里兼容多文件所以用数组接收。

Read more »
0%