springBoot之文件上傳與下載


注意:代碼的編寫是在建立Marven工程的基礎上編寫的

比較簡單,直接上代碼:

單文件上傳的服務端的代碼:

@RequestMapping(value = "/testUploadFile", method = RequestMethod.POST)
  public void testUploadFile(HttpServletRequest req,
      MultipartHttpServletRequest multiReq) {
    // 獲取上傳文件的路徑
    String uploadFilePath = multiReq.getFile("file1").getOriginalFilename();
    System.out.println("uploadFlePath:" + uploadFilePath);
    // 截取上傳文件的文件名
    String uploadFileName = uploadFilePath.substring(
        uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
    System.out.println("multiReq.getFile()" + uploadFileName);
    // 截取上傳文件的后綴
    String uploadFileSuffix = uploadFilePath.substring(
        uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
    System.out.println("uploadFileSuffix:" + uploadFileSuffix);
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      fis = (FileInputStream) multiReq.getFile("file1").getInputStream();
      fos = new FileOutputStream(new File(".//uploadFiles//" + uploadFileName
          + ".")
          + uploadFileSuffix);
      byte[] temp = new byte[1024];
      int i = fis.read(temp);
      while (i != -1){
        fos.write(temp,0,temp.length);
        fos.flush();
        i = fis.read(temp);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

 

多文件上傳服務端的代碼:

@RequestMapping(value = "testUploadFiles", method = RequestMethod.POST)
  @ResponseBody
  public void 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);
      if (!file.isEmpty()) {
        try {
          String uploadFilePath = file.getOriginalFilename();
          System.out.println("uploadFlePath:" + uploadFilePath);
          // 截取上傳文件的文件名
          String uploadFileName = uploadFilePath
              .substring(uploadFilePath.lastIndexOf('\\') + 1,
                  uploadFilePath.indexOf('.'));
          System.out.println("multiReq.getFile()" + uploadFileName);
          // 截取上傳文件的后綴
          String uploadFileSuffix = uploadFilePath.substring(
              uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
          System.out.println("uploadFileSuffix:" + uploadFileSuffix);
          stream = new BufferedOutputStream(new FileOutputStream(new File(
              ".//uploadFiles//" + uploadFileName + "." + uploadFileSuffix)));
          byte[] bytes = file.getBytes();
          stream.write(bytes,0,bytes.length);
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          try {
            if (stream != null) {
              stream.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      } else {
        System.out.println("上傳文件為空");
      }
    }
    System.out.println("文件接受成功了");
  }

 

下載文件服務端的代碼:

 @RequestMapping(value = "/testDownload", method = RequestMethod.GET)
  public void testDownload(HttpServletResponse res) {
    String fileName = "upload.jpg";
    res.setHeader("content-type", "application/octet-stream");
    res.setContentType("application/octet-stream");
    res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
      os = res.getOutputStream();
      bis = new BufferedInputStream(new FileInputStream(new File("d://"
          + fileName)));
      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();
        }
      }
    }
    System.out.println("success");
  }
}

 

瀏覽器端的界面代碼:

<!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="http://localhost:8080/testUploadFile" method="POST" enctype="multipart/form-data">
    <p>單文件上傳:</><br/>
    <input type="file" name="file1"/>
    <input type="submit" value = "上傳"/>
</form>
<form method="POST" enctype="multipart/form-data" 
    action="http://localhost:8080/testUploadFiles">
    <p>多文件上傳:</>
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p><input type="submit" value="上傳" /></p>
</form>
<a href="http://localhost:8080/testDownload">下載</a>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM