我的JSP:
<script language="javascript" src="js/event/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload(){
//开始上传文件时显示一个图片,文件上传完成将图片隐藏
//$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});
//执行上传文件操作的函数
$.ajaxFileUpload({
//处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
url:'${pageContext.request.contextPath}/uploadSave.do',
secureuri:false, //是否启用安全提交,默认为false
fileElementId:'imgFile', //文件选择框的id属性
dataType:'text', //服务器返回的格式,可以是json或xml等
success:function(data, status){ //服务器响应成功时的处理函数
data = data.replace(/<pre.*?>/g, ''); //ajaxFileUpload会对服务器响应回来的text内容加上<pre style="....">text</pre>前后缀
data = data.replace(/<PRE.*?>/g, '');
data = data.replace("<PRE>", '');
data = data.replace("</PRE>", '');
data = data.replace("<pre>", '');
data = data.replace("</pre>", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
if(data.substring(0, 1) == 0){ //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
$("img[id='uploadImage']").attr("src", data.substring(2));
$("img[id='uploadImage']").css("display", "");
$('#result').html("图片上传成功<br/>");
}else if(data.substring(0, 1) == 1){
$('#result').html('图片格式只能是jpg、jpeg、bmp、gif,请重试!!');
}else{
$('#result').html('图片上传失败,请重试!!');
}
},
error:function(data, status, e){ //服务器响应失败时的处理函数
$('#result').html('图片上传失败,请重试!!');
}
});
// $(document).getElementById("uploadForm").submit();
}
</script>
<img id="uploadImage" src="" style="display: none;width: 175px;height: 260px;"/>
<input name="myfiles" id="imgFile" type="file" value=""/> <br> <br>
<input type="button" value="上传" style="width:50px;height: 25px;"/>
@RequestMapping(value="uploadSave.do")
public String saveUpload(HttpServletRequest request,@RequestParam MultipartFile[] myfiles,HttpServletResponse response) throws IOException {
String path = "";
MultipartFile imgFileName = myfiles[0];
//
List fileTypes = new ArrayList();
fileTypes.add("jpg");
fileTypes.add("jpeg");
fileTypes.add("bmp");
fileTypes.add("gif");
String booleanString = "";
if(imgFileName.getOriginalFilename()!=null||!"".equals(imgFileName.getOriginalFilename())){
booleanString = this.getFile(imgFileName, fileTypes,request);
}
//设置响应给前台内容的PrintWriter对象
PrintWriter out = response.getWriter();
String outPrint = "0`" + "/upload/" + imgFileName.getOriginalFilename();
if("1".equals(booleanString)){
outPrint = "1`" + "/upload/" + imgFileName.getOriginalFilename();
}
out.print(outPrint);
out.flush();
return null;
}
private String getFile(MultipartFile imgFileName,List fileTypes,HttpServletRequest request)throws IOException {
String fileName = imgFileName.getOriginalFilename();
//获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
//对扩展名进行小写转换
ext = ext.toLowerCase();
String uploadFileName = "";
if(fileTypes.contains(ext)) { //如果扩展名属于允许上传的类型,则创建文件
// file = this.creatFolder(imgFileName,fileName);
String uploadPath = "/upload";
String realUploadFilePath = request.getSession().getServletContext().getRealPath(uploadPath);
String realUploadFileName = realUploadFilePath + File.separator + fileName;
uploadFileName = uploadPath + "/" + fileName;
// if(!StringUtils.isEmpty(dir)){
// realUploadFilePath = realUploadFilePath + File.separator + dir;
// uploadFilePath = uploadFilePath + "/" + dir;
// }
InputStream in = imgFileName.getInputStream();
moveFileToPath(in,realUploadFileName);
// try {
// imgFileName.transferTo(file); //保存上传的文件
// } catch (IllegalStateException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
} else{
uploadFileName = "1";
}
return uploadFileName;
}
public static void moveFileToPath(InputStream is,String path) throws IOException{
File newfile = new File(path);
// 新文件目录不存在,则创建
newfile = newfile.getParentFile();
if (!newfile.exists()){
newfile.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path);
int count = 0;
byte[] buffer = new byte[8192];
while ((count = is.read(buffer)) != -1){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}