使用ajax上传有多种方式,这里主要讲得是使用iframe,之前也使用过jquery的ajaxFileUpload插件做异步上传,但是这个插件对浏览器的兼容性不好,所以最后就放弃了,有兴趣的可以自己下载这个插件研究下,进入主题:
①文件上传方法:(这里就是一个简单的struts的上传,这里的文件路径是写死的,做项目的时候把路径放到配置文件中去是极好的)
public class FileUploadAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FileUploadAction.class);
private File file;
private String fileFileName;
private String fileFileContentType;
/**
* 响应请求:图片上传
* @return
* @throws Exception
*/
public String addAtta() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
response.setCharacterEncoding("UTF-8");
try{
String subRootPath = request.getSession().getServletContext().getRealPath("");
String attPath = FileUtil.uploadFile(file, fileFileName, request, "/upload/image/", subRootPath);
if(null != attPath) {
request.setAttribute("msg","11");
request.setAttribute("success", true); //设置成功否
request.setAttribute("imgUrl",attPath);
}
}catch (Exception e) {
e.printStackTrace();
log.error("附件上传失败", e);
response.getWriter().write("附件上传失败!");
}
return SUCCESS;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileFileContentType() {
return fileFileContentType;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
}
struts.xml配置
<action name="addAtta" class="com.****.***.action.FileUploadAction" method="addAtta">
<result name="success">/pages/shop/shopFileAdd.jsp</result>
</action>
需要做异步上传页面的代码块
<tr>
<th>
<span style="color: red">*</span>商品图片
</th>
<td colspan="5">
<input type="hidden" id="imgUrl"/>
<span style="white-space:pre"> </span> <span style="white-space:pre"> </span><input type="hidden" id="book_impUrl" name="productInfo.imgUrl"/>
<iframe name="iframeImgPage2" id="iframeImgPage2" height="50" scrolling="no" frameborder=0 src="${basePath}/pages/shop/shopFileAdd.jsp" ></iframe>
</td>
</tr>
iframe页面(shopFileAdd.jsp)----这个页面就是用来上传文件,如果是上传图片还可以用来进行图片回显
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/common/common.jsp"%>
<html>
<head>
<title>图片上传</title>
</head>
<script language="javascript">
//禁止页面刷新
document.onkeydown = function()
{
if(event.keyCode==116) {
event.keyCode=0;
event.returnValue = false;
}
}
document.oncontextmenu = function() {event.returnValue = false;}
function uploadPageLoad(){
var message = '<s:property value="#request.message" />';
var suffix = '<s:property value="#request.suffix" />';
var msg = '<s:property value="#request.success" />';
if(message!=''){
alert('文件类型'+suffix+'不符合上传类型');
return false;
}else if(msg) {
$("#paramForm").hide();
$("#img").show();
$("#delImg").show();
uploadImgUrl();
var pageHeight = $("#preview").height()+2;
window.parent.frames['iframeImgPage'].frameElement.height = pageHeight;
alert('上传文件成功');
}
if(msg == null || msg == "" || !msg){
var imgUrl = window.parent.document.getElementById("book_impUrl").value;
if(imgUrl != null && imgUrl != ""){
$("#book_impUrl").val(imgUrl);
$("#paramForm").hide();
$("#img").show();
$("#delImg").show();
$("#preview").attr('src', '${basePath}/' + imgUrl);
var pageHeight = $("#preview").height()+2;
window.parent.frames['iframeImgPage'].frameElement.height = pageHeight;
}
}
}
function delFileImgUrl(){
$("#paramForm").show();
window.parent.frames['iframeImgPage'].frameElement.height = 50;
//删除父页面的图片路径
window.parent.document.getElementById("book_impUrl").value = "";
$("#img").hide();
$("#delImg").hide();
}
function uploadImgUrl(){
var imgUrl = '<s:property value="#request.imgUrl" />';
window.parent.document.getElementById("book_impUrl").value = imgUrl;
$("#preview").attr('src', '${basePath}/' + imgUrl);
}
function validate() {
var filepath=$("input[name='upload']").val();
if(filepath == "") {
alert("请选择要上传的文件!");return;
}
var oldImgUrl = window.parent.document.getElementById("book_impUrl").value;
var srcImgUrl = window.parent.document.getElementById("imgUrl").value;
if(oldImgUrl != srcImgUrl){
$('#book_impUrl').val(oldImgUrl);
}
document.forms[0].submit();
}
$(document).ready(function(){
uploadPageLoad();
});
</script>
<body style="background-color:#FFF;">
<form id="paramForm" action="${basePath}/back/addAtta.action"
method="post" enctype="multipart/form-data">
<input type='file' name='file' enable='false'
contentEditable="false" />
<input type="button" οnclick="validate();" value="上传"
class="ImgButton" <s:if test='success'>disabled</s:if> />
</form>
<div id="img" style="display:none;font-size:12px;float:left;" align="absmiddle" >
<img id="preview" width="100" height="98" />
</div>
<p id="delImg" style="display: none;float:left;">
<a href="javascript:delFileImgUrl()">[删除]</a>
</p>
</body>
</html>