springboot学习(九): 文件的上传下载和jsp页面的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36553913/article/details/84197729

说明

由于工作的需要,在学习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

猜你喜欢

转载自blog.csdn.net/sinat_36553913/article/details/84197729