form表单
<form action="<c:url value="/restful/test/multipartUpload.do" />" method="post" enctype="multipart/form-data">
<div class="col-xs-12 martop10">
<input type="file" accept="*/*" name="uploadFile">
</div>
<div class="col-xs-12 martop10">
<button type="submit">开始上传</button>
</div>
</form>
后台处理
@RestController
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequestMapping("/restful/test")
public class restfulTestController extends AbsAppController {
protected final Logger LOG = LoggerFactory.getLogger(restfulTestController.class);
@UncheckAuth
@RequestMapping("/multipartUpload")
public Map<String, Object> multipartUpload(HttpServletRequest request, @RequestParam(
value = "uploadFile") CommonsMultipartFile commonsMultipartFile) {
//***************************************************************
// 获取项目的工作目录
// tempDirectoryPath=C:\Users\ADMINS~1\AppData\Local\Temp\
//***************************************************************
LOG.info("tempDirectoryPath="+FileUtils.getTempDirectoryPath());
//***********************************************************************
// 获取tomcat的工作目录
// tomcat catalina.base=D:\tomcat\apache-tomcat-7.0.72-mobile
//***********************************************************************
LOG.info("tomcat directory path="+System.getProperty("catalina.base"));
//************************************************************
// 获取项目的相对路径
// request.getContextPath()=/mobile
//************************************************************
LOG.info("request.getContextPath()="+request.getContextPath());
//***********************************************************************************************************
// 获取项目的绝对路径
// getServletContext().getRealPath("/")=D:\tomcat\apache-tomcat-7.0.72-mobile\webapps\izhuan-web-mobile\
//***********************************************************************************************************
LOG.info("request.getServletContext().getRealPath(\"/\")="+request.getServletContext().getRealPath("/"));
if (!commonsMultipartFile.isEmpty()) {
try {
// 文件保存路径
// String filePath = request.getServletContext().getRealPath("/") + "upload/" + commonsMultipartFile.getOriginalFilename();
String filePath = System.getProperty("catalina.base") + "/webapps/upload/" + commonsMultipartFile.getOriginalFilename();
// 转存文件
File folder = new File(filePath);
if (createDir(folder, filePath))
commonsMultipartFile.transferTo(folder);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
// 创建文件夹
public static boolean createDir(File folder, String url) throws IOException {
if (!folder.isFile()) {
if (!folder.exists()) {
folder.mkdirs();
}
}
// 检测是否创建成功
// folder.isDirectory() 校验文件是否存在,不做更新操作
// if (folder.isDirectory() && folder.exists())
// return true;
if (folder.exists())
return true;
return false;
}