1.使用form表单
accept属性的介绍点这里
<form id="fileForm">
<p>普通文本框:<input type="text" name="textInput"></p>
<!-- multiple表示可以选择多个文件 -->
<input type="file" name="file" id="file" multiple="multiple" accept="image/*">
<input type="button" value="提交 " id="submitFileForm">
</form>
$("#submitFileForm").click(function(){
var formData = new FormData($("#fileForm")[0]);
$.ajax({
url: '/uploadFile',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function(result){
alert(result.message);
}
})
});
@ResponseBody
@RequestMapping("uploadFile")
public String uplaodFile(HttpServletRequest request, HttpServletResponse response,
MultipartHttpServletRequest req) {
Map<String, Object> map = new HashMap<String, Object>();
//用到了jackson的jar包
ObjectMapper mapper = new ObjectMapper();
InputStream is = null;
OutputStream os = null;
try {
//普通文本
String str = request.getParameter("textInput");
//文件
List<MultipartFile> files = req.getFiles("file");
for(MultipartFile file : files) {
//对文件的大小、格式进行验证
long fileSize = file.getSize();
if(fileSize == 0) {
throw new RuntimeException("请选择文件!");
}
String fileName = file.getOriginalFilename();
String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
if(fileSize > 5242880) { //最大只能上传5M的(单位是字节)
throw new RuntimeException("文件大小不能超过5M!");
} else if(!".jpg".equals(fileSuffix) && !".png".equals(fileSuffix)) { //只能上传png、jpg的的图片
throw new RuntimeException("仅支持 png、jpg格式的文件!");
}else {
//文件符合要求进行上传操作
String newFileName = System.currentTimeMillis() + fileSuffix; //文件的新名字
String uploadPath = request.getSession().getServletContext().getRealPath("");
uploadPath += "/upload";
File f = new File(uploadPath);
if(!f.exists()) {
f.mkdirs();
}
is = file.getInputStream();
os = new FileOutputStream(uploadPath + "/" + fileName);
byte[] b = new byte[1024];
int len= 0;
while((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
}
}
}catch (Exception e) {
e.printStackTrace();
map.put("message", e.getMessage());
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}
} finally {
try {
if(is != null) {
is.close();
}
if(os != null) {
os.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
map.put("message", "上传成功!");
try {
return mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
2.不使用form表单
后台可以和上面使用一样的,就js部分有一点不一样
<input type="file" name="file" id="file" multiple="multiple" accept="image/*">
<input type="button" value="提交 " id="submitFileForm">
$("#submitFileForm").click(function(){
var formData = new FormData();
var file = $("#file")[0].files;
for(var i = 0; i < file.length; i++){
formData.append("file", file[i]);
}
$.ajax({
url: '/uploadFile',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function(result){
alert(result.message);
}
})
});