在网上看完很多人写的ajax文件上传代码都说自己的能实现无刷新上传文件,结果都不行的,有的人还不用form表单直接写个html的file input获取本地图片的路径就说能上传,真的太无语了SB啊这么能忽悠人!今天哥要纠正一下他们的错误,图片上传不管理直接提交还是异步提交都要用用到form还带
enctype:'multipart/form-data',
标签,否则无法上传,不信你做个给我看!
好了费话不多讲直接上代码!
服务器端处理代码
package cn.min.springmvc;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class UploadController {
@RequestMapping("/up")
public String upload(){
return "upload";
}
@SuppressWarnings("unchecked")
@RequestMapping(value="/upfile",params="json=true")
@ResponseBody
public void upfile(HttpServletRequest req,HttpServletResponse res) throws IOException{
System.out.println("调用");
String path = req.getSession().getServletContext().getRealPath("/upload/");
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
Iterator iter = multiRequest.getFileNames();
String fileName= "";
String origFileName ="";
List li =new ArrayList();
int i=0;
while(iter.hasNext()){
MultipartFile mfile = multiRequest.getFile((String)iter.next());
//获得原始文件名
origFileName = mfile.getOriginalFilename();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String suffix = origFileName.substring(origFileName.lastIndexOf(".")).toLowerCase();
fileName = format.format(new Date())+i+suffix;
File f = new File( path +"/"+fileName.toLowerCase());
try {
mfile.transferTo(f);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
li.add("{fileName:'"+fileName+"'}");
System.out.println(fileName);
i++;
}
res.getWriter().write(li.toString());
System.out.println(li);
}
}
js代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax File Upload </title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(function(){
$("#up").click(function(){
$("#upload").ajaxSubmit({
url:"/upload/upfile?json=true",
type:"post",
enctype:'multipart/form-data',
iframe: true,
dataType:"text",
success:function(data, status){
//alert(data);
data= eval('('+data+')');
var imgs = "";
for(i=0;i<data.length;i++) {
imgs+= "<img src='upload/"+data[i].fileName+"'/>";
}
$("#show").append(imgs);
}
});
});
var id= 1;
$("#add").click(function(){
id=id+1;
var tr ="<tr id=\"t"+(id)+"\"><td><input type=\"file\" name=\"pic["+(id)+"]\" class=\"pic\"></td><td><a href=\"javascript:void(0)\" id="+(id)+" class=\"del\">X</a></td></tr>";
$("#tb").append(tr);
$(".del").click(function(){//不能放到外面
var tid = "t"+$(this).attr("id");
$("#"+tid).remove();
})
})
})
</script>
</head>
<body>
<form id="upload" action="upfile" method="post" enctype="multipart/form-data">
<table id="tb">
<tr>
<td><input type="file" name="pic[1]" class="pic"></td>
<td><a href="javascript:void(0)" class="del">X</a></td>
</tr>
</table>
<input type="button" value="excute" id="up">
</form>
<a href="javascript:void(0)" id="add">add</a>
<div id="show"> </div>
</body>
</html>