功能概述:实现了利用ajaxfileupload.js上传文件
jsp:
<body>
<div align="center">
<label for="upload">上传图片:</label> <input type="file" name="upload"
id="upload"> <br /> <input type="button" class="uploadImg"
value="ajaxfileupload.js异步上传图片">
</div>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript">
$(function() {
$(".uploadImg").click(function() {
$.ajaxFileUpload({
url : 'UploadImgDemo.action',//后台请求地址
type : 'post',//请求方式 当要提交自定义参数时,这个参数要设置成post
secureuri : false,//是否启用安全提交,默认为false。
fileElementId : 'upload',// 需要上传的文件域的ID,即<input type="file">的ID。
dataType : 'content',//服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。如果json返回的带pre,这里修改为json即可解决。
async : true, //是否是异步
success : function(data, status) {//提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
if (data == "<pre>ok</pre>") {
alert("上传成功111");
} else {
alert("上传成功222");
}
},
error : function(data, status, e) {//提交失败自动执行的处理函数。
alert("上传失败!");
}
});
});
});
</script>
</body>
action:
@Controller
@ParentPackage("json-default")
public class UploadAction extends ActionSupport {
private File upload;// 要上传的文件
private String uploadFileName;// 上传文件的名字
private String path;// 路径
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
/**
* ajaxfileupload.js实现异步上传图片
*/
@Action(value = "UploadImgDemo", results = { @Result(name = "success", type = "json") })
public String UploadImgDemo() {
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
ServletActionContext.getResponse().setContentType("text/json; charset=UTF-8");
String ret = "";
try {
// 设置文件保存的路径
path = ServletActionContext.getServletContext().getRealPath("/upload/");
File file = new File(path);
if (!file.exists()) {//如果文件夹不存在则自动创建
file.mkdir();
}
// 将页面传过来的数据通过FileUtils 拷贝到我们刚刚定义的路径
FileUtils.copyFile(upload, new File(file, uploadFileName));
String file2 = new File(file, uploadFileName).toString();// 文件保存的全路径名,包含文件名
ret="ok";
PrintWriter out = ServletActionContext.getResponse().getWriter();
out.write(ret);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
}