SpringMVC文件上传,下载

SpringMVC文件上传,下载


控制类

package com.mvc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Scope("prototype")
@RequestMapping("toFile")
public class MulitPartFileController {
	//单文件上传
	@RequestMapping("/upolad.do")
	public ModelAndView upolad(@RequestParam("emgFile") MultipartFile file,HttpServletRequest request){
		System.out.println("单文件上传..");	
		//获得上传文件目录 和名称
		String path=request.getSession().getServletContext().getRealPath("/")+"upfile/";
		String fileName=file.getOriginalFilename();
		//创建目标文件
		File filepath=new File(path);	
		if(!filepath.exists())
		{
			filepath.mkdirs();
		}
		//保存
		try {
			File fi=new File(path+fileName);
			file.transferTo(fi);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	
		return new ModelAndView("admin/success");
	}
	
	//多文件上传
	@RequestMapping(value="/upolads.do")
	public ModelAndView  upolads(HttpServletRequest request){
	
		//获得N个文件
		MultipartHttpServletRequest mrequest=(MultipartHttpServletRequest)request;
		//获得文件名称
		Iterator<String> its=mrequest.getFileNames();
		while(its.hasNext()){	
			MultipartFile file=mrequest.getFile(its.next());
			//这里可以判断...文件格式,啥啥的...
			
			//获得上传文件目录 和名称
			String path=request.getSession().getServletContext().getRealPath("/")+"upfile/";
			String fileName=file.getOriginalFilename();	
			//创建目标文件
			File filepath=new File(path);
			if(!filepath.exists())
			{
				filepath.mkdirs();
			}
			//保存
			try {
				File fi=new File(path+fileName);
				file.transferTo(fi);
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
		return new ModelAndView("admin/success");
	}
	
	//下载
	@RequestMapping(value="/downloadFile.do")
	public  ModelAndView downloadFile(String fileName,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		//设置响应的文件类型和文件编码
		 response.setContentType("text/html;charset=utf-8");
		//确保请求的编码类型为UTF-8,不然文件下载后有可能因为类型不一致出现乱码
		 request.setCharacterEncoding("UTF-8");
	 
    	//设置下载文件的内容响应
		response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
	   //下载路径
		String path=request.getSession().getServletContext().getRealPath("/")+"upfile/"+fileName;
	   //获得输入流
		FileInputStream fis=new FileInputStream(new File(path));
	   //输出流
		OutputStream os=response.getOutputStream();
	   //读写操作
		int len=0;
		byte[] bt=new byte[1024];
		while((len=fis.read(bt))>0){
			os.write(bt, 0, len);
		}
		
		os.close();
		fis.close();
		
	  return null; 
	}
}
applicationContext.xml配置

	<!-- 文件上传解析器  -->
	<bean  id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		 <!-- 设定默认编码 -->
		<property name="defaultEncoding" value="UTF-8" />
		 <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
		<property name="maxUploadSize" value="5242880" />
		<property name="maxInMemorySize" value="4096" />	
	</bean>

jsp页面

单文件上传
<form action="${pageContext.request.contextPath}/toFile/upolad.do" method="post" enctype="multipart/form-data">
<input type="file" name="emgFile"><br>
<input type="submit" value="上传">	
</form>
------------------------------------------------------------------
多文件上传
<form action="${pageContext.request.contextPath}/toFile/upolads.do" method="post" enctype="multipart/form-data">
<input type="file" name="file1"><br>
<input type="file" name="file2"><br>
<input type="file" name="file3"><br>
<input type="submit" value="上传">	
</form>
------------------------------------------------------------------
文件下载
<a href="toFile//downloadFile.do?fileName=卡拉.jpg">卡拉.jpg</a>
<a href="toFile//downloadFile.do?fileName=Jellyfish.jpg">Jellyfish.jpg</a>
------------------------------------------------------------------

这里还需要这一个jar包
在这里插入图片描述

注意点

这里说一哈,可能在测试的时候出现400错误,这个可能是你的

public ModelAndView upolad(@RequestParam("emgFile") MultipartFile file,HttpServletRequest request){...}

这里命名的错误,最好不要 @RequestParam(“emgFile”) 中的参数名和 MultipartFile 定义的参数名一样
还有 是 “@RequestParam(“emgFile”)” 不是 “ @RequestPart(“emgFile”)”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值