ajax异步上传文件

来源:互联网 发布:007支票打印软件 编辑:程序博客网 时间:2024/04/30 10:01

第一步: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

0 0
原创粉丝点击