服务器之家

服务器之家 > 正文

Spring boot 实现单个或批量文件上传功能

时间:2021-05-26 12:18     来源/作者:佳佳乐2503

一:添加依赖:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- thymeleaf模板插件 -->
  <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-thymeleaf</artifactid>
  </dependency>
   <!-- jsp依赖 -->
<dependency>
  <groupid>javax.servlet</groupid>
  <artifactid>jstl</artifactid>
</dependency>
<dependency>
  <groupid>org.apache.tomcat.embed</groupid>
  <artifactid>tomcat-embed-jasper</artifactid>
  <!--<scope>provided</scope>-->
</dependency>

二:application.xml配置文件路径:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#配置上传文件地址
image.location.path=f:/image/
#配置文件大小限制
spring.http.multipart.maxfilesize=100mb
spring.http.multipart.maxrequestsize=100mb
#静态页面的访问配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=html5

三:编写静态页面(src/main/resources下建文件夹static(static存放静态文件,比如 css、js、image…)和templates(存放静态页面)两个是同级目录),先在templates 中新建一个 uploadimg.html。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!doctype html>
<html>
 <head>
  <title>uploadimg.html</title>
  <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
  <meta name="description" content="this is my page"></meta>
  <meta name="content-type" content="text/html; charset=utf-8"></meta>
  <!--<link rel="stylesheet" type="text/css" href="./styles.css" rel="external nofollow" >-->
 </head>
 <body>
 <form enctype="multipart/form-data" method="post" action="/dc/fileupload">
  图片<input type="file" name="file"/>
  <input type="submit" value="上传"/>
  </form>
 </body>
</html>

四:编写controller层:

?
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.hot.analysis.controller.file;
import java.io.bufferedinputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.outputstream;
import java.util.date;
import java.util.random;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.springframework.beans.factory.annotation.value;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.servlet.modelandview;
import com.hot.analysis.exception.myexception;
@restcontroller
public class fileuploadcontroller {
 //获取配置文件的路径
 @value("${image.location.path}")
 private string resourcedir;
 /**
   * 实现文件上传
   * */
 @requestmapping(value = "/index")
 public modelandview toindex() {
 modelandview mv = new modelandview("uploadimg");
 return mv;
 }
  //单个文件上传
  @requestmapping("/dc/fileupload")
  @responsebody
  public string fileupload( multipartfile file){
   // 获取上传文件路径
    string uploadpath = file.getoriginalfilename();
    // 获取上传文件的后缀
    string filesuffix = uploadpath.substring(uploadpath.lastindexof(".") + 1, uploadpath.length());
    if (filesuffix.equals("apk")) {
    uploadpath = resourcedir;
    } else {
    // 上传目录地址
    // string uploadpath="e:/hot-manage/image/";//windows路径
    uploadpath =resourcedir;// liux路劲
    }
    // 上传文件名
    string filename = new date().gettime() + new random().nextint(100) + "." + filesuffix;
    file savefile = new file(uploadpath + filename);
    if (!savefile.getparentfile().exists()) {
    savefile.getparentfile().mkdirs();
    }
    try {
    file.transferto(savefile);
    } catch (illegalstateexception e) {
    e.printstacktrace();
    } catch (ioexception e) {
    e.printstacktrace();
    }
    if (filesuffix.equals("apk")) {
    return "/apk/" + filename;
    } else {
    return "/image/" + filename;
    }
   }
 // 批量上传
  @postmapping("/dc/morefileupload")
 public string bacthfileupload(multipartfile[] file) throws myexception {
  stringbuffer buffer = new stringbuffer();
  for (multipartfile multipartfile : file) {
  string str = fileupload(multipartfile);
  buffer.append(str);
  buffer.append(",");
  }
  string all = buffer.substring(0, buffer.length() - 1);
  return all;
 }
 // 删除文件
  @postmapping("/dc/deletefile")
  public string delfile(string path) {
   string resultinfo = null;
 int lastindexof = path.lastindexof("/");
 string sb = path.substring(lastindexof + 1, path.length());
 sb = "f:/image/" + sb;
 file file = new file(sb);
 if (file.exists()) {
  if (file.delete()) {
  resultinfo = "1-删除成功";
  } else {
  resultinfo = "0-删除失败";
  }
 } else {
  resultinfo = "文件不存在!";
 }
 return resultinfo;
 }
 //文件下载相关代码
  @requestmapping("/download")
  public string downloadfile(httpservletrequest request, httpservletresponse response) {
    string filename = "aim_test.txt";// 设置文件名,根据业务需要替换成要下载的文件名
    if (filename != null) {
      //设置文件路径
      string realpath = "d://aim//";
      file file = new file(realpath , filename);
      if (file.exists()) {
        response.setcontenttype("application/force-download");// 设置强制下载不打开
        response.addheader("content-disposition", "attachment;filename=" + filename);// 设置文件名
        byte[] buffer = new byte[1024];
        fileinputstream fis = null;
        bufferedinputstream bis = null;
        try {
          fis = new fileinputstream(file);
          bis = new bufferedinputstream(fis);
          outputstream os = response.getoutputstream();
          int i = bis.read(buffer);
          while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
          }
          system.out.println("success");
        } catch (exception e) {
          e.printstacktrace();
        } 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;
  }
 
  }

测试:

Spring boot 实现单个或批量文件上传功能

成功返回路径:

Spring boot 实现单个或批量文件上传功能

查看文件夹:

Spring boot 实现单个或批量文件上传功能

总结

以上所述是小编给大家介绍的spring boot 实现单个或批量文件上传功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://blog.csdn.net/qq_33355858/article/details/81747101

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部