首先需要两个jar文件
commons-io-2.5.jar
commons-fileupload-1.3.1.jar
当然版本根据自己需要选择
设置文件上传配置,在spring配置文件,加入文件上传配置
<!--文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
html文件
<form action="/fileController/upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Submit" /></form>
package com.neutron.admin.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.http.HttpField;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.neutron.admin.model.dto.Json;
/**文件上传处理**/
@Controller
@RequestMapping("/fileController")
public class FileController {
@RequestMapping("/upload")
@ResponseBody
public Json upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) throws IllegalStateException, IOException{
Json json=new Json();
//文件上传路径
String path= request.getSession().getServletContext().getRealPath("/upload");
String fileName=file.getOriginalFilename();
File tfile=new File(path,fileName);
if(!tfile.exists()){//没有路径,自动创建 这里路径在项目文件夹下
tfile.mkdirs();
}
file.transferTo(tfile);
json.setMsg(request.getContextPath()+"/upload/"+fileName);
return json;
}
}