SpringMVC 实现文件的上传与下载

https://www.cnblogs.com/xuningchuanblogs/p/7683866.html

一  配置SpringMVC ,并导入与文件上传下载有关的jar包(在此不再赘述)

二 新建 相应 jsp 和controller

FileUpAndDown.jsp

复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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="${pageContext.request.contextPath}/fileUpLoad" method="post"  enctype="multipart/form-data">
文件名<input type="file" name="photo"/><br/>
     <input type="text" name="desc"/> <br/>
     <input type="submit" value="提交"/><br/>
</form>
<h3>童话镇.mp3  陈一发儿</h3>
<a href="${pageContext.request.contextPath}/fileDownLoad">前去下载</a>
</body>
</html>
复制代码
复制代码

package
com.neuedu.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller public class FileUpAndDown { @RequestMapping(value="/fileUpLoad") public String testUpload(HttpServletRequest request,@RequestParam(value="desc",required=false) String desc,@RequestParam("photo") CommonsMultipartFile file) throws Exception{ ServletContext servletContext = request.getServletContext();//获取ServletContext的对象 代表当前WEB应用 String realPath = servletContext.getRealPath("/uploads");//得到文件上传目的位置的真实路径 System.out.println("realPath :"+realPath); File file1 = new File(realPath); if(!file1.exists()){ file1.mkdir(); //如果该目录不存在,就创建此抽象路径名指定的目录。 } String prefix = UUID.randomUUID().toString(); prefix = prefix.replace("-",""); String fileName = prefix+"_"+file.getOriginalFilename();//使用UUID加前缀命名文件,防止名字重复被覆盖 InputStream in= file.getInputStream();;//声明输入输出流 OutputStream out=new FileOutputStream(new File(realPath+"\\"+fileName));//指定输出流的位置; byte []buffer =new byte[1024]; int len=0; while((len=in.read(buffer))!=-1){ out.write(buffer, 0, len); out.flush(); //类似于文件复制,将文件存储到输入流,再通过输出流写入到上传位置 } //这段代码也可以用IOUtils.copy(in, out)工具类的copy方法完成 out.close(); in.close(); return "success"; } @RequestMapping("/fileDownLoad") public ResponseEntity<byte[]> fileDownLoad(HttpServletRequest request) throws Exception{ ServletContext servletContext = request.getServletContext(); String fileName="童话镇.mp3"; String realPath = servletContext.getRealPath("/WEB-INF/"+fileName);//得到文件所在位置 InputStream in=new FileInputStream(new File(realPath));//将该文件加入到输入流之中 byte[] body=null; body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数 in.read(body);//读入到输入流里面 fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码 HttpHeaders headers=new HttpHeaders();//设置响应头 headers.add("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode = HttpStatus.OK;//设置响应吗 ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode); return response; //public ResponseEntity(T body, // MultiValueMap < String,String > headers, // HttpStatus statusCode) //HttpEntity使用给定的正文,标题和状态代码创建一个新的。 //参数: //body - 实体机构 //headers - 实体头 //statusCode - 状态码 } }
复制代码

JSP界面:

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Spring MVC的文件下载功能,需要进行以下步骤: 1、引入Apache Commons FileUpload组件的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2、配置文件解析器。在Spring MVC的配置文件中,配置一个MultipartResolver的Bean用于处理文件请求。 3、创建文件的表单。在HTML表单中,设置enctype为"multipart/form-data",并添加一个文件选择框。 4、创建文件的控制器。在控制器中,使用MultipartFile参数接收上文件,并执行相应的操作,比如保存文件到指定位置。 5、创建文件下载的控制器。在控制器中,使用ResponseEntity<byte[]>对象来实现文件下载,设置相应的响应头信息,如Content-Disposition和文件名。 下面是一个示例的代码,演示了如何实现文件下载: ``` // 文件的控制器 @Controller public class FileUploadController { @RequestMapping("/fileUpload") public String testFileUpload(MultipartFile photo, HttpSession session) throws IOException { String filename = photo.getOriginalFilename(); ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("photo"); File file = new File(realPath); if (!file.exists()) { file.mkdir(); } String finalPath = realPath + File.separator + filename; photo.transferTo(new File(finalPath)); return "success"; } } // 文件下载的控制器 @Controller public class FileDownloadController { @RequestMapping("/fileDownload") public ResponseEntity<byte[]> testFileDownload(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("static/img/a.jpg"); InputStream inputStream = new FileInputStream(realPath); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=a.jpg"); HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status); inputStream.close(); return responseEntity; } } // 文件的表单 <form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="photo" multiple> <input type="submit" value="上"/> </form> ``` 通过以上步骤,你可以在Spring MVC中实现文件的上下载功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值