form表单
<form id="formfile" action="slideshowin" method="post" enctype="multipart/form-data">
<input type="button" id="buttonf" οnclick="buttonfunction()" value="增加图片" />
<input type="file" name="file" οnchange="fileupload()" id="files" />
</form>
ajxa提交表单
function fileupload() {
获取表单,必须加[0]才能取到数据
var formData =new FormData($("#formfile")[0]);
$.ajax({
url: url,
type: "POST",
data: formData,
cache:false,
contentType: false,
processData: false,
success: function (dat) {
},
error: function (dat) {
}
});
}
后台代码 spring的
MultipartFile类,必须在xml配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
public String insert(@RequestParam("file")MultipartFile file,HttpServletRequest request)throws IOException {
if(!file.isEmpty()){
获取后缀名
String suffix =file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//设置允许上传文件类型
String suffixList = "jpg,png,ico,bmp,jpeg";
判断是否包含
if(suffixList.contains(suffix.trim().toLowerCase()))""){
保存文件的路径
String path = request.getSession().getServletContext().getRealPath("")+"slideImg/"+file.getOriginalFilename();
查看路径是否存在,不存在就创建
//image/jpeg
if(!new File(path).exists()){
new File(path).mkdirs();
}
spring的transferTo保存文件方法
file.transferTo(new File(path));
Slideshow slideshow=new Slideshow();
slideshow.setSlideshowImg(file.getOriginalFilename());
slideshow.setSlideshowState(0);
slideshow.setSlideshowTime(new DataTime().getDatatime());
slideshowService.insert(slideshow);
return "成功!";
}
return "图片格式不正确!";
}
return "未选择图片!";
}