spring之文件上传下载

1.首先创建一个用来测试的jsp文件上传下载的页面 代码如下

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

文件上传下载 选择文件:
2.在自己已经构建好的maven web项目中 pom.xml配置文件中添加上传下载所需要的jar包
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>

3.在spring的applicationContext.xml配置文件中添加文件上传解析器

4.在controller层实现上传下载的代码

package com.chao.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**

  • 下载 测试
  • @author 王一土

*/
@Controller
@RequestMapping(“file”)
public class UoloadController {

@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody  
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{  
    String path = request.getSession().getServletContext().getRealPath("upload");  
    String fileName = file.getOriginalFilename();    
    File dir = new File(path,fileName);          
    if(!dir.exists()){  
        dir.mkdirs();  
    }  
   
    file.transferTo(dir);  
    return fileName;  
}  

   @RequestMapping("/down")  
    public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{  
       
        String fileName = request.getSession().getServletContext().getRealPath("upload")+"/101.jpg";  
        
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));  
          
        String filename = "下载文件.jpg";  
        
        filename = URLEncoder.encode(filename,"UTF-8");  
        
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
            
        response.setContentType("multipart/form-data");   
        
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
        int len = 0;  
        while((len = bis.read()) != -1){  
            out.write(len);  
            out.flush();  
        }  
        out.close();  
    }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值