栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

在SpringMVC框架下实现文件的上传和下载示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在SpringMVC框架下实现文件的上传和下载示例

在eclipse中的javaEE环境下:导入必要的架包

web.xml的配置文件:



 
   
  
    springDispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:springmvc.xml
    
    1
  

  
    springDispatcherServlet
    /
  
 
  
   
     HiddenHttpMethodFilter
     org.springframework.web.filter.HiddenHttpMethodFilter
   
   
   
     HiddenHttpMethodFilter
     /*
   
 
 

spring的bean的配置文件springmvc.xml;



  
  
  
  
  
  
    
    
  
  
  
  
  
  
   
  
   
    
     
    
    
   
  

 handler类方法:实现文件的上传和下载的方法

 @Controller
public class SpringMVCTest {
  
  @Autowired
  private EmployeeDao employeeDao;
  //实现文件的下载
  //需要说明的是文件的上传和下载不需要其他配置
  @RequestMapping("testResponseEntity")
  public ResponseEntity testResponseEntity(HttpSession session) throws IOException{
    
    byte[] body=null;
    ServletContext servletContext=session.getServletContext();
    ///files/abc.txt:所要下载文件的地址
    InputStream in=servletContext.getResourceAsStream("/files/abc.txt");
    body=new byte[in.available()];
    in.read(body);
    
    HttpHeaders headers=new HttpHeaders();
    //响应头的名字和响应头的值
    headers.add("Content-Disposition", "attachment;filename=abc.txt");
    
    HttpStatus statusCode=HttpStatus.OK;
    
    ResponseEntity response=new ResponseEntity(body, headers, statusCode);
    return response;
  } 
  //文件上传,
     @RequestMapping("/testFileUpload")
     public String testFileUpload(@RequestParam("desc") String desc,
      @RequestParam("file") MultipartFile file) throws IOException{

      System.out.println("desc:"+desc);
      System.out.println("OriginalFilename"+file.getOriginalFilename());
      System.out.println("InputStream"+file.getInputStream());
      return "success";
   }
 } 

jsp页面:index.jsp:

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




Insert title here


  
  
     

Test ResponseEntity

success.jsp页面:显示文件上传成功

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




Insert title here


  
  Success page
  


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/147634.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号