欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解SpringBoot下文件上传与下载的实现

程序员文章站 2023-11-29 12:25:22
springboot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传与下载。前端上传采用百度webuploader插件。有关该插件的使用方法还在研究中,日后整理...

springboot后台如何实现文件上传下载?

最近做的一个项目涉及到文件上传与下载。前端上传采用百度webuploader插件。有关该插件的使用方法还在研究中,日后整理再记录。本文主要介绍springboot后台对文件上传与下载的处理。

单文件上传

/ 单文件上传
@requestmapping(value = "/upload")
@responsebody
public string upload(@requestparam("file") multipartfile file) {
  try {
  if (file.isempty()) {
    return "文件为空";
  }
  // 获取文件名
  string filename = file.getoriginalfilename();
  logger.info("上传的文件名为:" + filename);
  // 获取文件的后缀名
  string suffixname = filename.substring(filename.lastindexof("."));
  logger.info("文件的后缀名为:" + suffixname);

  // 设置文件存储路径
  string filepath = "d://aim//";
  string path = filepath + filename + suffixname;

  file dest = new file(path);
  // 检测是否存在目录
  if (!dest.getparentfile().exists()) {
    dest.getparentfile().mkdirs();// 新建文件夹
  }
  file.transferto(dest);// 文件写入
  return "上传成功";
  } catch (illegalstateexception e) {
    e.printstacktrace();
  } catch (ioexception e) {
    e.printstacktrace();
  }
  return "上传失败";
}

如果想要修改文件路径及文件名,修改filepath以及filename即可。

多文件上传

/多文件上传
@requestmapping(value = "/uploadmore", method = requestmethod.post)
@responsebody
public string handlefileupload(httpservletrequest request) {
  list<multipartfile> files = ((multiparthttpservletrequest) request).getfiles("file");
  multipartfile file = null;
  bufferedoutputstream stream = null;
  for (int i = 0; i < files.size(); ++i) {
    file = files.get(i);
    string filepath = "d://aim//";
    if (!file.isempty()) {
      try {
        byte[] bytes = file.getbytes();
        stream = new bufferedoutputstream(new fileoutputstream(
            new file(filepath + file.getoriginalfilename())));//设置文件路径及名字
        stream.write(bytes);// 写入
        stream.close();
      } catch (exception e) {
        stream = null;
        return "第 " + i + " 个文件上传失败 ==> "
            + e.getmessage();
      }
    } else {
      return "第 " + i
          + " 个文件上传失败因为文件为空";
    }
  }
  return "上传成功";
}

文件下载

//文件下载相关代码
@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;
}

multipartconfig配置

可以通过multipartconfig配置类对文件上传进行全局控制。

@configuration
public class multipartconfig {

  @bean
  public multipartconfigelement multipartconfigelement() {
    multipartconfigfactory factory = new multipartconfigfactory();
    // 置文件大小限制 ,超出此大小页面会抛出异常信息
    factory.setmaxfilesize("2mb"); //kb,mb
    // 设置总上传数据总大小
    factory.setmaxrequestsize("20mb");
    // 设置文件临时文件夹路径
    // factory.setlocation("e://test//");
    // 如果文件大于这个值,将以文件的形式存储,如果小于这个值文件将存储在内存中,默认为0
    // factory.setmaxrequestsize(0);
    return factory.createmultipartconfig();
  }
}

注意事项

前后端文件传输格式应为 multipart/form-data

以上所述是小编给大家介绍的springboot下文件上传与下载的实现详解整合,希望对大家有所帮助