当前位置: 移动技术网 > IT编程>开发语言>Java > springboot 中文件上传下载实例代码

springboot 中文件上传下载实例代码

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

spring boot是由pivotal团队提供的全新框架,其设计目的是用来简化新spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,spring boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

spring boot特点

1. 创建独立的spring应用程序

2. 嵌入的tomcat,无需部署war文件

3. 简化maven配置

4. 自动配置spring

5. 提供生产就绪型功能,如指标,健康检查和外部配置

6. 绝对没有代码生成和对xml没有要求配置[

springboot 实现文件上传下载实例代码如下所示:

@controller
public class fileuploadctrl {
 @value("${file.upload.dir}")
 private string path;
 /**
  * 实现文件上传
  * */
 @requestmapping(value = "/fileupload", method = requestmethod.post)
 @responsebody
 public map<string,object> fileupload(@requestparam("filename") multipartfile file){
  map<string,object> map = new hashmap<string, object>();
  int no = 0;
  string msg = "上传失败!";
  if(!file.isempty()){
   string filename = file.getoriginalfilename();
   file dest = new file(path + "/" + filename);
   if(!dest.getparentfile().exists()){ //判断文件父目录是否存在
    dest.getparentfile().mkdir();
   }
   try {
    file.transferto(dest); //保存文件
    no = 1;
    msg = "上传成功!";
   } catch (illegalstateexception e) {
    e.printstacktrace();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
  map.put("no",no);
  map.put("msg", msg);
  return map;
 }
 @requestmapping(
   value = "/filedownload",
   method = requestmethod.get
 )
 public responseentity<?> getgwfilecontent(@requestparam string filename,@requestparam int flag) {
  httpheaders headers = new httpheaders();
  headers.add("cache-control", "no-cache, no-store, must-revalidate");
  string filepath = path+"/"+filename;;
  inputstream is = null;
  try {
   headers.add("content-disposition", string.format("attachment; filename=\"%s\"", new string(filename.getbytes("gbk"), "iso8859-1")));
   if(flag==0){//表示获取缩略图
    file file = new file(filepath);
    filepath = path+"/xx"+filename;
    file xxfile = new file(filepath);
    if(!xxfile.exists()){//不存在就生成缩略图
     thumbnails.of(file).scale(0.25f).tofile(xxfile);
    }
   }
   is = new fileinputstream(new file(filepath));
  } catch (unsupportedencodingexception e) {
   e.printstacktrace();
  } catch (filenotfoundexception e) {
   e.printstacktrace();
  } catch (ioexception e) {
   e.printstacktrace();
  }
  headers.add("pragma", "no-cache");
  headers.add("expires", "0");
  return responseentity
    .ok()
    .headers(headers)
    .contenttype(mediatype.parsemediatype("application/octet-stream"))
    .body(new inputstreamresource(is));
 }
}

总结

以上所述是小编给大家介绍的springboot 中文件上传下载实例代码,希望对大家有所帮助

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

相关文章:

验证码:
移动技术网