1. 程式人生 > >springboot學習(九): 檔案的上傳下載和jsp頁面的使用

springboot學習(九): 檔案的上傳下載和jsp頁面的使用

說明

由於工作的需要,在學習springboot時,學習了jsp的使用,最近又涉及到springboot的檔案上傳方式。找資料學習後,在這裡記錄總結下springboot的單個和多個檔案的上傳和下載及jsp的使用。

正文

一、jsp的使用

通過Spring Initializr建立新的springboot專案,新增依賴:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-tomcat</artifactId>
	<scope>provided</scope>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<scope>provided</scope>
</dependency>
<!-- jstl -->
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>

<!-- tomcat-embed-jasper -->
<dependency>
	<groupId>org.apache.tomcat.embed</groupId>
	<artifactId>tomcat-embed-jasper</artifactId>
	<scope>provided</scope>
</dependency>

新增依賴後,在application.properties中配置檔案的字首和字尾:

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
#關閉預設模板引擎
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=false

啟動類繼承SpringBootServletInitializer,重寫configure方法:

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
	return builder.sources(FilehandlingApplication.class);
}

二、檔案上傳

單個檔案上傳

建立檔案上傳的jsp頁面

<form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="上傳">
</form>

在方法的中使用 MultipartFile作為引數型別

 @RequestMapping(value = "/upload",method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
 public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
      System.out.println(file.getOriginalFilename());
      File covertFile = new File("F:/StudyProject/springboot_studyII/filehandling/" + file.getOriginalFilename());
      covertFile.createNewFile();
      FileOutputStream fout = new FileOutputStream(covertFile);
      fout.write(file.getBytes());
      fout.close();
      return "file is upload successfully";
 }

使用ajax上傳多個檔案

建立jsp頁面,這裡使用ajax非同步上傳,需要jquery.jsjquery.form.js外掛 :

<script type="text/javascript" src="<%=basePath%>/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/jquery.form.js"></script>

表單元素

<form action="#" method="POST" enctype="multipart/form-data" id="upload-form">
   <input type="file" name="files"/><br/>
   <input type="file" name="files"/><br/>
   <input type="file" name="files"/><br/>

   <input type="submit" value="上傳" id="upload">
</form>

使用ajax非同步上傳

<script>
    $(function () {
        $("#upload").bind('click',function () {
            var option = {
                url:'<%=basePath%>/upload/multi',
                type:'post',
                async:true,
                enctype:'multipart/form-data',
                dataType:'text',
                success: function (data) {
                    alert(data);
                },
                error:function () {
                   alert("upload failed!");
                }
            };
            $("#upload-form").ajaxSubmit(option);
        });
    });
</script>

在上傳方法中使用MultipartFile[]作為引數型別

@RequestMapping(value = "/upload/multi", method = RequestMethod.POST)
public String mutliFileUplod(@RequestParam(value = "files") MultipartFile[] files){
    for(MultipartFile file : files){
        System.out.println(file.getOriginalFilename());
    }
    return "multiple files upload successfully";
}

檔案下載

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<Object> downloadFile() throws FileNotFoundException {
    String fileName = "C:/Users/wds/Desktop/test.txt";
    File file = new File(fileName);
    InputStreamResource resource = new InputStreamResource(new FileInputStream((file)));

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition",String.format("attachment;filename=\"%s\"",file.getName()));
    headers.add("Cache-Control","no-cache,no-store,must-revalidate");
    headers.add("Pragma","no-cache");
    headers.add("Expires","0");

    ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/text")).body(resource);
    return responseEntity;
}

可以通過引數指定檔案的下載地址,訪問方法結果如下圖所示:
在這裡插入圖片描述

原始碼地址:https://github.com/Edenwds/springboot_study/tree/master/filehandling

參考資料:
https://howtodoinjava.com/spring-boot/spring-boot-jsp-view-example/
https://www.tutorialspoint.com/spring_boot/spring_boot_file_handling.htm