Spring MVC
- maven
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
- spring配置
<!--文件上传依赖配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="209715200"/>
<property name="resolveLazily" value="true"/>
</bean>
<!--添加aop,用于新建上传目录-->
<aop:aspectj-autoproxy/>
<bean id="fileAop" class="org.yiva.exam.aop.FileAop"/>
- 编码
前端
<form id="upload" class="layui-form" action="${base}/file/doUpload" method="post" enctype="multipart/form-data">
<div class="layui-form-item">
<label class="layui-form-label">上传文件</label>
<div class="layui-input-block">
<input type="file" name="uploadFile" required lay-verify="required" placeholder="请输入部门名称"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDept">立即提交</button>
</div>
</div>
</form>
controller
@PostMapping(value = {"doUpload"})
@ResponseBody
public String upload(@RequestParam("uploadFile") MultipartFile file) throws IOException {
logger.info(file.getOriginalFilename());
if (!file.isEmpty()) {
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(CommonsInfo.UPDATE_PATH, file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
return "fail";
}
aop
@Aspect
public class FileAop {
private Logger logger = Logger.getLogger(FileAop.class);
@Pointcut("execution(* org.yiva.exam.controller.FileController.upload(..))")
public void poincutFile(){
}
/**
* 在访问上传文件功能前判断是否已经存在上传文件的保存目录,如没有则新建
*/
@Before(value = "poincutFile()")
public void before(JoinPoint joinPoint) throws IOException {
File folder = new File(CommonsInfo.UPDATE_PATH);
if (!folder.isDirectory() || !folder.exists()) {
folder.mkdirs();
logger.info("create Directory updateFile");
}
}
}