SpringMVC实现文件上传与下载

网友投稿 293 2022-10-24


SpringMVC实现文件上传与下载

本文实例为大家分享了SpringMVC实现文件上传与下载的具体代码,供大家参考,具体内容如下

0.环境准备

1.maven依赖

org.junit.jupiter

junit-jupiter-api

5.7.0

test

javax.servlet

javax.servlet-api

3.1.0

provided

org.springframework

spring-webmvc

5.2.6.RELEASE

commons-io

commons-io

2.8.0

commons-fileupload

commons-fileupload

1.3.3

2.springConfig。xml配置文件

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context

https://springframework.org/schema/context/spring-context.xsd

http://springframework.org/schema/mvc https://springframework.org/schema/mvc/spring-mvc.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context

https://springframework.org/schema/context/spring-context.xsd

http://springframework.org/schema/mvc https://springframework.org/schema/mvc/spring-mvc.xsd">

3.web.xml配置

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

web

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:springConfig.xml

1

web

*.mvc

characterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

utf-8

forRequestEncoding

true

forResponseEncoding

true

characterEncodingFilter

/*

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

web

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:springConfig.xml

1

web

*.mvc

characterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

utf-8

forRequestEncoding

true

forResponseEncoding

true

characterEncodingFilter

/*

1.文件上传

文件上传分为三种方式:

单个文件单字段

多个文件单字段

多个文件多字段

注意点:

1、提交方式为表单的post请求

2、from属性augYetNMT中必须有enctype=“multipart/form-data”

3、如果是单字段多文件:输入框中的属性必须为:multiple=“multiple”

4、表单中的属性name必须和后端参数一致

1.前端代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

文件上传(单个文件单字段上传)

文件上传(多文件单字段上传)

文件上传(多文件多字段上传)

2.后端代码

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

import java.io.File;

import java.io.IOException;

/**

* @author compass

* @version 1.0

* @date 2021-05-11 14:33

*/

@Controller

public class UploadIFileController {

// 处理单个文件上传

@PostMapping("/uploadFile1.mvc")

public ModelAndView uploadFile1(MultipartFile file, HttpSession session) throws IOException {

ModelAndView view = new ModelAndView();

// 得到文件名称

String filename=file.getOriginalFilename();

System.out.println("文件名称:"+filename);

if (!file.isEmpty()){

// 判断文件的后缀

if (filename.endsWith(".jpg")||filename.endsWith(".png")||filename.endsWith(".txt"));

//设置文件的保存路径

String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file";

File srcFile = new File(savePath,filename);

// 执行文件保存操作

file.transferTo(srcFile);

view.setViewName("forward:/uploadSuccess.jsp");

}else {

view.setViewName("forward:/uploadFailed.jsp");

}

return view;

}

// 处理多文件上传

@PostMapping("/uploadFile2.mvc")

public ModelAndView uploadFile2(MultipartFile[] file,HttpSession session) throws IOException {

ModelAndView view = new ModelAndView();

//设置文件的保存路径

String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file";

String[] filenames = new String[file.length];

// 只要上传过来的文件为空或者是不符合指定类型的都会上传失败

for (int i = 0; i

// 判断上传过来的文件是否为空

if (!file[i].isEmpty()){

String filename=file[i].getOriginalFilename();

// 判断文件类型

if (filename.endsWith(".txt")||filename.endsWith(".jpg")||filename.endsWith(".png")){

// 创建一个文件对象

File srcFile = new File(savePath, filename);

// 执行保存文件操作

file[i].transferTo(srcFile);

view.setViewName("forward:/uploadSuccess.jsp");

}else {

view.setViewName("forward:/uploadSuccess.jsp");

}

}else {

view.setViewName("forward:/uploadFailed.jsp");

}

}

return view;

}

}

2.文件下载

文件下分为两种情况:

文件名称是纯英文字母的

文件名带有中文不处理会乱码的

1.前端代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

// 判断上传过来的文件是否为空

if (!file[i].isEmpty()){

String filename=file[i].getOriginalFilename();

// 判断文件类型

if (filename.endsWith(".txt")||filename.endsWith(".jpg")||filename.endsWith(".png")){

// 创建一个文件对象

File srcFile = new File(savePath, filename);

// 执行保存文件操作

file[i].transferTo(srcFile);

view.setViewName("forward:/uploadSuccess.jsp");

}else {

view.setViewName("forward:/uploadSuccess.jsp");

}

}else {

view.setViewName("forward:/uploadFailed.jsp");

}

}

return view;

}

}

2.文件下载

文件下分为两种情况:

文件名称是纯英文字母的

文件名带有中文不处理会乱码的

1.前端代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

2.后端代码

/**

* @author compass

* @version 1.0

* @date 2021-05-11 15:23

*/

@Controller

public class DownloadController {

// 非中文名称文件下载

@GetMapping("/download1.mvc")

public ResponseEntity fileDownload1(String filename,HttpServletRequest request) throws IOException {

String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file\\";

File file = new File(path,filename);

HttpHeaders header = new HttpHeaders();

header.setContentDispositionFormData("attachment",filename);

header.setContentType(MediaType.APPLICATION_OCTET_STREAM);

ResponseEntity result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);

return result;

}

// 中文名称文件下载

@GetMapping("/download2.mvc")

public ResponseEntity fileDownload2(String filename,HttpServletRequest request) throws IOException {

System.out.println(filename);

String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file\\";

filename = filename.replace("_", "%");

filename= URLDecoder.decode(filename,"UTF-8");

String downloadFile="";

if (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie")>0){

filename= URLEncoder.encode(filename,"UTF-8");

downloadFile=filename.replaceAll("+","%20");

}else {

downloadFile=new String(filename.getBytes("UTF-8"),"ISO-8859-1");

}

File file = new File(path,filename);

HttpHeaders header = new HttpHeaders();

header.setContentDispositionFormData("attachment",downloadFile);

header.setContentType(MediaType.APPLICATION_OCTET_STREAM);

ResponseEntity result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);

return result;

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:加密芯片SPI通讯的调试
下一篇:OSI的七层模型
相关文章

 发表评论

评论列表