当前位置: 移动技术网 > IT编程>开发语言>Java > springboot实现文件上传和下载功能

springboot实现文件上传和下载功能

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring boot 引入”约定大于配置“的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心。大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码。

1.文件上传(前端页面):

<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>insert title here</title> 
</head> 
<body> 
<form action="/testupload" method="post" enctype="multipart/form-data"> 
 <input type="file" name="file"/> 
 <input type="submit" /> 
</form> 
<a href="/testdownload" rel="external nofollow" >下载</a> 
</body> 
</html>

 表单提交加上enctype="multipart/form-data"很重要,文件以二进制流的形式传输。

2.文件上传(后端java代码)支持多文件

way1.使用multiparthttpservletrequest来处理上传请求,然后将接收到的文件以流的形式写入到服务器文件中:

@requestmapping(value="/testupload",method=requestmethod.post) 
 public void testuploadfile(httpservletrequest req,multiparthttpservletrequest multireq) throws ioexception{ 
  fileoutputstream fos=new fileoutputstream(new file("f://test//src//file//upload.jpg")); 
  fileinputstream fs=(fileinputstream) multireq.getfile("file").getinputstream(); 
  byte[] buffer=new byte[1024]; 
  int len=0; 
  while((len=fs.read(buffer))!=-1){ 
   fos.write(buffer, 0, len); 
  } 
  fos.close(); 
  fs.close(); 
 } 

way2.也可以这样来取得上传的file流:

// 文件上传
 @requestmapping("/fileupload")
 public map fileupload(@requestparam("file") multipartfile file, httpservletrequest req) {
  map result = new hashmap();
  simpledateformat df = new simpledateformat("yyyymmdd");// 设置日期格式
  string datedir = df.format(new date());// new date()为获取当前系统时间
  string servicename = uuidutil.get32uuid()
    + file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof("."));
  file tempfile = new file(filedir + datedir + file.separator + servicename);
  if (!tempfile.getparentfile().exists()) {
   tempfile.getparentfile().mkdirs();
  }
  if (!file.isempty()) {
   try {
    bufferedoutputstream out = new bufferedoutputstream(new fileoutputstream(tempfile));
    // "d:/"+file.getoriginalfilename() 指定目录
    out.write(file.getbytes());
    out.flush();
    out.close();
   } catch (filenotfoundexception e) {
    e.printstacktrace();
    result.put("msg", "上传失败," + e.getmessage());
    result.put("state", false);
    return result;
   } catch (ioexception e) {
    e.printstacktrace();
    result.put("msg", "上传失败," + e.getmessage());
    result.put("state", false);
    return result;
   }
   result.put("msg", "上传成功");
   string fileid = get8uuid.generateshortuuid();
   string filename = file.getoriginalfilename();
   string filetype = filename.substring(filename.lastindexof(".") + 1);
   string fileurl = webdir + datedir + '/' + servicename;
   uploadmapper.savefileinfo(fileid, servicename, filetype, fileurl);
   result.put("state", true);
   return result;
  } else {
   result.put("msg", "上传失败,因为文件是空的");
   result.put("state", false);
   return result;
  }

3.application.properties配置文件

#上传文件大小设置
multipart.maxfilesize=500mb
multipart.maxrequestsize=500mb

4.文件下载将文件写到输出流里:

@requestmapping(value="/testdownload",method=requestmethod.get) 
public void testdownload(httpservletresponse res) throws ioexception{ 
 file file = new file("c:/test.txt");
  resp.setheader("content-type", "application/octet-stream");
  resp.setcontenttype("application/octet-stream");
  resp.setheader("content-disposition", "attachment;filename=" + filename);
  byte[] buff = new byte[1024];
  bufferedinputstream bis = null;
  outputstream os = null;
  try {
  os = resp.getoutputstream();
  bis = new bufferedinputstream(new fileinputstream(file));
  int i = bis.read(buff);
  while (i != -1) {
  os.write(buff, 0, buff.length);
  os.flush();
  i = bis.read(buff);
  }
  } catch (ioexception e) {
  e.printstacktrace();
  } finally {
  if (bis != null) {
  try {
  bis.close();
  } catch (ioexception e) {
  e.printstacktrace();
  }
  }
 }

} 

5.获取文件大小

// 文件大小转换
decimalformat df1 = new decimalformat("0.00");
string filesizestring = "";
long filesize = file.getsize();
if (filesize < 1024) {
 filesizestring = df1.format((double) filesize) + "b";
 } else if (filesize < 1048576) {
 filesizestring = df1.format((double) filesize / 1024) + "k";
 } else if (filesize < 1073741824) {
 filesizestring = df1.format((double) filesize / 1048576) + "m";
 } else {
 filesizestring = df1.format((double) filesize / 1073741824) + "g";
 }

如果是file类则filesize=file.length()。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网