<script type="text/javascript" src="jsp/jquery.min.js"></script>
<!-- 同步 -->
<form id="aa" action="myfile" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交"/>
</form>
<!-- 异步 -->
<input type="button" id="but" value="确定">
<script type="text/javascript">
$("#but").click(function(){
var targetUrl = $("#aa").attr("action");
var data = new FormData($( "#aa" )[0]);
$.ajax({
type:'post',
url:targetUrl,
cache: false, //上传文件不需缓存
processData: false, //需设置为false。因为data值是FormData对象,不需要对数据做处理
contentType: false, //需设置为false。因为是FormData对象,且已经声明了属性enctype="multipart/form-data"
data:data,
dataType:'json',
success:function(){
alert('success');
}
})
});
</script>
package com.csgg.Controller;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@RequestMapping("/myfile")
public String myfile(MultipartFile file) throws IllegalStateException, IOException {
System.out.println("=========================="+file);
if(file!=null) {
//获取文件名
String name = file.getOriginalFilename();
File file2=new File("D:\\快牙\\",name);
file.transferTo(file2);
System.out.println("上传成功!");
}
return "";
}
}