加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax异步上传文件

发布时间:2020-12-15 21:51:55 所属栏目:百科 来源:网络整理
导读:第一步:jsp页面写一个file类型的输入框 input type="file" name='testFile' id="violateItemUpload" onchange='uploadRecordFile()' / 第二步:在js里写异步ajax上传文件 注:使用异步ajax前,要额外导入一个js文件。当然,jquery的js文件肯定不能少。 pre

第一步:jsp页面写一个file类型的输入框

<input type="file"  name='testFile'  id="violateItemUpload" onchange='uploadRecordFile()' />

第二步:在js里写异步ajax上传文件

注:使用异步ajax前,要额外导入一个js文件。当然,jquery的js文件肯定不能少。

<pre name="code" class="javascript"><script type="text/javascript" src="js/jquery.js" ></script> 
<script type="text/javascript" src="/jqueryUpload/ajaxfileupload.js" ></script> 
<pre name="code" class="html">//记录中新增文件图片(记录ID)
		function uploadRecordFile(val){
			$.ajaxFileUpload  
	        ({  
	                url: 'test!uploadRecordFile.action',secureuri: false,fileElementId: 'violateItemUpload',dataType: 'html',beforeSend: function() {  
	                    $("#loading").show();  
	                },complete: function() {  
	                    $("#loading").hide();  
	                },success: function(data,status) { 
	               if(data=="error"){
	            	   $.messager.alert('提醒',"系统出错,请联系管理员","error");
	               }else{//data可传过来代表是否文件保存成功,也可以传过来保存成功后的文件路径
<img src="${pageContext.request.contextPath}/qstdUploadAction!queryEndorsementFile2.action?path="+data />//通过流的形式把图片显示出来 
} 
}
} )
return false; 
}


 

第三步:后台JAVA代码,用的是Struts2的action方式。

public class TestAction extends PaginationAction {

private File testFile;

public File getTestFile() {
        return testFile;
    }

    public void setTestFile(File testFile) {
        this.testFile= testFile;
    }

public String uploadRecordFile() {
        try {
            String path = RequestPath.root + RequestPath.test;//保存文件的路径
            File file = new File(path);
            file.mkdirs();
            String fileName = recordId + "_" + System.currentTimeMillis()
                    + ".jpg";
            boolean isSave = FileUploadUtil.upload(testFile,path,fileName);//保存文件到指定的地址,成功则返回路径
            if (isSave) {
                writeMsg(path + fileName);
            } else {
                writeMsg("error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("错误信息:",e);
        }

        return null;
    }

}


根据上面说明的三步骤,即可实现文件的异步上传。


ajaxfileupload.js文件下载地址:http://download.csdn.net/detail/shi_hong_fei_hei/7596803

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读