file

index.html

<div>
<form method="post" action="upload.html" enctype="multipart/form-data" id="sub">
   <input type="text" name="name" />
   <input type="file" name="file" />
   <input type="button" value="提交表单" οnclick="doit();"/>
   
  </form>
  <script>
  	function doit(){
  		$("#sub").submit();
  	}
  </script>
</div> 

SPRING MVC config file  xxx-servlet.xml
 
	<context:component-scan base-package="net.spring.controller" />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
		p:defaultEncoding="UTF-8" >
		<property name="maxUploadSize">
             <value>1048576</value>
         </property>		
FileOperateController.java
package net.spring.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileOperateController implements ServletContextAware {

	private ServletContext servletContext;

	@RequestMapping(value = "/upload")
	public ModelAndView upload(@RequestParam("name") String name,
			@RequestParam("file") CommonsMultipartFile mFile) throws Exception {
		System.out.println("mFile:"+mFile.isEmpty());
		System.out.println("name:"+name);
		if (!mFile.isEmpty()) {
			String path = this.servletContext.getRealPath("/") + "temp/"; // 获取本地存储路径
			File abpath = new File(path);
			if (!abpath.exists()) {
				abpath.mkdir();
			}
			File file = new File(path + mFile.getOriginalFilename()); // 新建一个文件
			mFile.getFileItem().write(file);
			return null; // 返回成功视图
		} else {
			return null; // 返回成功视图
		}
	}

	@Override
	public void setServletContext(ServletContext arg0) {
		// TODO Auto-generated method stub
		this.servletContext = arg0;
	}
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值