最近做了一个文件上传 用ajaxfileupload.js 在火狐 谷歌 IE9及以上版本可用 为了兼容IE8 找到了jquery-form.js
html 代码:
<form id="form1" name="form1" runat="server" method="post" enctype="multipart/form-data">
<input type="file" name="fileName" id="fileName" />
<a class="easyui-linkbutton" iconCls="icon-up" onclick="upload()" href="javascript:void(0);">上传</a>
</form>
js代码:
function upload(){
if($("#fileName").val()==""){
$.messager.alert("操作提示","请点击浏览按钮 选择文件");
return false;
}
var form = $("form[name=form1]");
var options = {
url:'${ctx}/CostMsg/upFile',
type:'post',
data:{'id':$("#chargesId").val()},
success:function(data)
{
var jsondata = eval("("+data+")");
if(jsondata.success){
$("#fileName").val("");
var fileName = jsondata.msg;
$("#chargesId").val(jsondata.obj);
var html="<div style='float:left;margin:5px'><div onclick='deleteImage(this);'><img style='float:right' src='${static}/js/jquery-easyui-1.2.6/themes/icons/cancel.png'/></div><a href='javascript:void(0);' style='margin:5px' ><img src='${static}/uploadFiles/chargesFile/"+fileName+"' width='140' height='140' /></a></div>";
$('#upImage').append(html);
}else{
var message = jsondata.msg;
$("#messageTip").html("<span style='color:red'>"+message+"</span>");
}
}
};
form.ajaxSubmit(options);
}
controllor代码:
/**
* 文件上传
* @param apkFile
* @param request
* @param id
* @return Json
*/
@RequestMapping(value = "/upFile")
@ResponseBody
public void upFile(@RequestParam("fileName") MultipartFile fileName,HttpServletRequest request,HttpServletResponse response,String id) {
try {
Json json=new Json();
response.setContentType("text/html");
json=CostMsgService.upFile(fileName,request, response,id);
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(JSONObject.toJSONString(json));
} catch (IOException e) {
e.printStackTrace();
}
}
service代码:
@Override
public Json upFile(MultipartFile file,HttpServletRequest request,HttpServletResponse response,String id) {
Json json=new Json();
try {
String[] types=new String[]{".jpg",".png",".jpeg",".bmp",".zip",".JPG",".PNG",".JPEG",".BMP",".ZIP"};
// 文件保存目录路径
String savePath = request.getSession().getServletContext().getRealPath("/")+ "static/"+Upload_Directory;
// 文件保存目录URL
String saveUrl = request.getContextPath() +"/static/"+ Upload_Directory;
// 定义允许上传的文件扩展名
File inbox = new File(savePath); //判断文件夹是否存在
if (!inbox.exists()) {
inbox.mkdirs();
}
File inbox1 = new File(saveUrl); //判断文件夹是否存在
if (!inbox1.exists()) {
inbox1.mkdirs();
}
// 最大文件大小
long maxSize = 3145728;
if (!ServletFileUpload.isMultipartContent(request)) {
json.setMsg("请选择文件");
json.setSuccess(false);
return json;
}
String originFileName=file.getOriginalFilename();
String suffix=originFileName.indexOf(".") !=-1?
String str = System.currentTimeMillis()+"";
String newFileName=str+suffix;
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
// 检查文件大小
if (file.getSize() > maxSize) {
json.setMsg("上传文件大小超过限制。最大3M");
json.setSuccess(false);
return json;
}
// 检查扩展名
if (!Arrays.<String> asList(types).contains(suffix)) {
json.setMsg("上传文件扩展名是不允许的扩展名。\n只允许jpg,jpeg,png,bmp,zip 格式。");
json.setSuccess(false);
return json;
}
IdGenerator idG=new IdGenerator();
String chargesId=id;
if(id==null||id.length()==0){
chargesId=idG.getLongValue()+"";
}
if(suffix!=null){
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(savePath, newFileName));
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(saveUrl, newFileName));
CostMsgDao.executeSql("insert into t_jy_file (ID,TABLE_ID,FILE_NAME,TABLE_NAME) values('"+str+"','"+chargesId+"','"+newFileName+"','t_jy_deductionrecord')");
json.setMsg(newFileName);
json.setObj(chargesId);
json.setSuccess(true);
logger.error("file upload success:"+originFileName+" file length is"+file.getSize());
return json;
}else {
logger.error("不能识别该文件 或文件已损坏:"+originFileName);
return json;
}
} catch (Exception e) {
e.printStackTrace();
return json;
}
}
该代码已经过测试 并上线使用