springMVC初步学习(七)

  此篇博客是关于使用springMVC进行文件上传的。

1.在springMVC-servlet.xml中添加相关的Bean,如下:

    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        <!-- 指定所上传文件的总大小不能超过。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
        <property name="maxUploadSize" value="10485760000"/> 
        <property name="defaultEncoding" value="utf-8"/> 
        <property name="maxInMemorySize" value="40960"/> 
    </bean> 

2.添加相关jar包,分别是:

com.springsource.org.apache.commons.fileupload-1.2.0.jar

com.springsource.org.apache.commons.io-1.4.0.jar

3.文件上传的jsp页面必须注意的地方,自己老是只记得要修改enctype,而忘记修改method属性为post,代码如下:

	<form action="/springMVC2/file/upload"   enctype="multipart/form-data" method="post">
	
		<input type="file" name="file">
		<input type="submit" value="上传文件">
	
	
	</form>
4. Controller的代码:

package com.study.controller.annotation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping("/file")
public class UploadController {
	
	@RequestMapping("/upload")//@RequestParam中的file对应jsp页面中的  name="file"
	public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws Exception{
		
		String fileName = file.getOriginalFilename();//必须是这个获取文件名的函数
		//System.out.println(fileName);
		//System.out.println(request.getContextPath());
		File storeFile = new File(request.getRealPath("storefile"));
		System.out.println(storeFile.getAbsolutePath());
		OutputStream os = new FileOutputStream(new File(storeFile,fileName));
		InputStream  is = file.getInputStream();
		
		int b;
		while((b = is.read()) != -1){
			os.write(b);
		}
		
		request.setAttribute("fileName", fileName);
		
		return "/uploadsuccess";
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值