ssm框架下fileupload图片上传实践

参考这篇博客操作http://blog.csdn.net/jronzhang/article/details/61210700

1、加入两个jar包,commons-fileupload-1.3.jar、commons-io-1.2.jar

2、在配置文件applicationContext.xml加上以下配置

<!-- 定义文件解释器(文件上传) -->  
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
    <!-- 设置默认编码 -->  
    <property name="defaultEncoding" value="utf-8"></property>  
    <!-- 上传图片最大大小1M-->   
    <property name="maxUploadSize" value="1048576"></property>    
</bean>


3、Controller层写java代码

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/file")
public class FileController {
	
	
	@RequestMapping("/test.do")
	@ResponseBody
	public String test(MultipartFile file,HttpServletRequest request) throws IOException{
		System.out.println("comming!");
		String path = request.getSession().getServletContext().getRealPath("/images");
		System.out.println("path>>"+path);

		String fileName = file.getOriginalFilename();
		System.out.println("fileName>>"+fileName);
		
		File dir = new File(path, fileName);
		System.out.println("dir.exists()>>"+dir.exists());
		if(!dir.exists()){
			dir.mkdirs();
		}
		System.out.println("dir.exists()>>"+dir.exists());
//		MultipartFile自带的解析方法
		file.transferTo(dir);
		
		return "ok";
	}
}


5、html和js

<form id="test">  
	选择文件:<input data-role="none" type="file" name="file" width="120px">  
	<button data-role="none" onclick="testUpload();">测试</button>
</form>
function testUpload(){
	var form = new FormData(document.getElementById("test"));
	var url = 项目访问路径 + "/file/test.do";    //这里的“项目访问路径”要改为你自己的路径
	$.ajax({
		url : url,
		data : form,
		type : 'post',
		processData:false,
        contentType:false,
        success : function(data){
        	alert("成功")
        },
        error : function(data){
        	
        }
	});
}


这样就大功告成,上传的图片在tomcat目录的

\webapps\你的项目名\images

里面

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值