首页 > 代码库 > spring boot实现文件上传下载

spring boot实现文件上传下载

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">下载</a>  </body>  </html>  

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

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

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

@RequestMapping(value="http://www.mamicode.com/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=500Mbmultipart.maxRequestSize=500Mb

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

@RequestMapping(value="http://www.mamicode.com/testDownload",method=RequestMethod.GET)      public void testDownload(HttpServletResponse res) throws IOException{          String fileName="upload.jpg";          res.setHeader("content-type", "application/octet-stream");          res.setContentType("application/octet-stream");          res.setHeader("Content-Disposition", "attachment;filename=CourseResource.jpg");          File file=new File("F://BaiduYunDownload//testRedis//src//file//upload.jpg");                    FileOutputStream fos=new FileOutputStream(file);                res.setContentLengthLong(file.length());          fos.close();      }  

 

spring boot实现文件上传下载