我用的是这个:https://github.com/carlcarl/AjaxFileUpload
下载地址在这里:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar
AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。
当初做了个异步上传的功能,选择它因为它的配置方式比较像jQuery的AJAX,我很喜欢。
ajaxFileUpload是一个异步上传文件的jQuery插件
语法:$.ajaxFileUpload([options])
options参数说明:
1、url 上传处理程序地址。
2,fileElementId 需要上传的文件域的ID,即的ID。
3,secureuri 是否启用安全提交,默认为false。
4,dataType 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success 提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error 提交失败自动执行的处理函数。
7,data 自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8, type 当要提交自定义参数时,这个参数要设置成post
错误提示:
1,SyntaxError: missing ; before statement错误
如果出现这个错误就需要检查url路径是否可以访问
2,SyntaxError: syntax error错误
如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
3,SyntaxError: invalid property id错误
如果出现这个错误就需要检查文本域属性ID是否存在
4,SyntaxError: missing } in XML expression错误
如果出现这个错误就需要检查文件name是否一致或不存在
5,其它自定义错误
大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。
使用方法:
第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>
第二步:HTML代码:
<div class="tab-pane fade in active" id="systemConfig" >
<form id="photoUploadForm">
<div class="input-group">
<span class="input-group-addon">项目名称:</span>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="input-group" style="margin-top: 25px;">
<p><input type="file" id="uploadFile" name="uploadFile"/></p>
<input type="button" class="btn btn-primary" value="保存" onclick="shangchuan()" style="margin-top: 25px;"/>
</div>
</form>
</div>
第三步:JS代码
function shangchuan() {
ajaxFileUpload();
}
function ajaxFileUpload() {
var name=$("#name").val();
alert(name);
$.ajaxFileUpload
(
{
url: '/update/ajaxFileUpload?name='+name, //用于文件上传的服务器端请求地
method:"post",
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'uploadFile', //文件上传域的ID
dataType: 'json', //返回值类型 一般设置为json
//data:$("#photoUploadForm").serialize(),
success: function (data, status) //服务器成功响应处理函数
{
},
error: function (data, status, e)//服务器响应失败处理函数
{
}
}
)
return false;
}
第四步:后台FileUploadController代码:
package com.metro.crm.controller.base.controller;
import com.metro.crm.entity.SysConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 本地上传
* @author
*
*/
@Controller
@RequestMapping
public class FileUploadController {
private static final Log logger = LogFactory.getLog(FileUploadController.class);
/** 上传文件名 */
private static final String UPLOAD_FILE_NAME = "uploadFile";
/**
* 前端获取服务器绝对路径图片
* @param fileName
* @param response
*/
@RequestMapping(value = "/update/getImg", method = RequestMethod.GET)
public void getImg(String fileName , HttpServletResponse response){
File f = new File(fileName);
try {
String file = fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
Image image = ImageIO.read(f);
if(image == null){
String fileExt = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()).toLowerCase();
response.setContentType("application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;fileName="+file);
}
FileCopyUtils.copy(new FileInputStream(f), response.getOutputStream());
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
@ResponseBody
@RequestMapping(value = "/update/ajaxFileUpload", method = RequestMethod.POST)
public Map<String,Object> ajaxFileUpload(HttpServletRequest request, HttpServletResponse response,SysConfig sysConfig){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile uploadFile = multipartRequest.getFile(UPLOAD_FILE_NAME);
Map<String, Object> map = new HashMap<String, Object>();
if (uploadFile == null) {
map.put("status", "error");
map.put("message", "上传失败:文件为空");
return map;
}
try {
//1.文件存储在临时目录上
String fileName = uploadFile.getOriginalFilename();
//获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
String fileExt = fileName.substring(fileName.lastIndexOf("."),fileName.length()).toLowerCase();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newName = sdf.format(new Date());
//获取当前项目根目录
String path = request.getSession().getServletContext().getRealPath("");
File filePath=new File(path);
path = filePath.getParentFile().getParent()+"/upload";
//获取文件夹位置(用作判断文件夹是否存在)
File file =new File(path);
logger.info(file);
//如果文件夹不存在则创建
if (!file .exists() && !file .isDirectory()){
//创建upload目录
file.mkdir();
}
//把图片放在项目根目录的上一级目录(防止系统更新导致文件丢失)
path+= "/"+newName+fileExt;
File f = new File(path);
//前端获取绝对路径图片
String frontImg = "/update/getImg?fileName="+path;
//保存到指定目录
uploadFile.transferTo(f);
map.put("status", "success");
map.put("message","上传成功" );
//返回给kindEditor
map.put("url",frontImg );
return map;
} catch (IOException e) {
String msg = "上传文件失败:"+e.getMessage();
logger.info("=========="+msg);
map.put("status", "error");
map.put("message",msg );
return map;
}
}
}
项目运行效果图: