AjaxFileUpload(1)Simple File Upload Sample
AjaxFileUpload(1)SimpleFileUploadSample
1.MavenConfiguration
Thejardependeciesinpom.xmlareasfollow:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
2.AddtionalSpringConfiguration
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="maxUploadSize"value="104857600"/>
<propertyname="maxInMemorySize"value="4096"/>
<propertyname="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
3.MyJavaScriptandHTMLpage
<html>
<head>
<title>AjaxFileUploadDemo</title>
<scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<scripttype="text/javascript"src="./resources/component/ajaxfileupload/2.1/ajaxfileupload.js"></script>
<scripttype="text/javascript">
$(document).ready(function(){
$("#filemaps").change(function(){
varfile_upl=document.getElementById('filemaps');
varrealpath=getPath(file_upl);
$("#fileurl").val(realpath);
});
});
functionuserBrowser(){
varbrowserName=navigator.userAgent.toLowerCase();
if(/msie/i.test(browserName)&&!/opera/.test(browserName)){
return"IE";
}elseif(/firefox/i.test(browserName)){
return"Firefox";
}elseif(/chrome/i.test(browserName)&&/webkit/i.test(browserName)&&/mozilla/i.test(browserName)){
return"Chrome";
}elseif(/opera/i.test(browserName)){
return"Opera";
}elseif(/webkit/i.test(browserName)&&!(/chrome/i.test(browserName)&&/webkit/i.test(browserName)&&/mozilla/i.test(browserName))){
return"Safari";
}else{
return"unKnow";
}
}
functiongetPathIE(obj){
obj.select();
returndocument.selection.createRange().text;
}
functiongetPathFFSecurity(obj){
try{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}catch(e){
alert('Unabletoaccesslocalfilesduetobrowsersecuritysettings.Toovercomethis,followthesesteps:(1)Enter"about:config"intheURLfield;(2)RightclickandselectNew->Boolean;(3)Enter"signed.applets.codebase_principal_support"(withoutthequotes)asanewpreferencename;(4)ClickOKandtryloadingthefileagain.');
if(obj.files){
returnobj.files.item(0).name;
}
return;
}
returnobj.value;
}
functionextractFilename(path){
if(path.substr(0,12)=="C:\\fakepath\\")
returnpath.substr(12);//modernbrowser
varx;
x=path.lastIndexOf('/');
if(x>=0)//Unix-basedpath
returnpath.substr(x+1);
x=path.lastIndexOf('\\');
if(x>=0)//Windows-basedpath
returnpath.substr(x+1);
returnpath;//justthefilename
}
functiongetPath(obj){
if(obj){
//if(window.navigator.userAgent.indexOf("MSIE")>=1){
if(userBrowser()=='IE'){
returngetPathIE(obj);
//}elseif(window.navigator.userAgent.indexOf("Firefox")>=1){
}elseif(userBrowser()=='Firefox'){
returngetPathFFSecurity(obj);
}elseif(userBrowser()=='Chrome'){
returnextractFilename(obj.value);
}
returnobj.value;
}
}
functionajaxFileUpload(){
$.ajaxFileUpload(
{
url:'fileupload.do',
secureuri:false,
fileElementId:'filemaps',
dataType:'json',
success:function(data,status)
{
console.info(data);
$('#result').html('SuccesstoAdd');
},
error:function(data,status,e)
{
$('#result').html('FailtoAdd');
}
}
);
}
</script>
</head>
<body>
<h2>AjaxFileUploadDemo</h2>
<formmethod="post"action="fileupload.do"enctype="multipart/form-data">
<inputid="fileurl"type="text"class="langtext"readonly="readonly"/>
<inputtype="file"id="filemaps"name="filemaps"value="upload"/>
<inputtype="button"value="Submit"onclick="ajaxFileUpload()"/>
</form>
<divid="result"></div>
</body>
</html>
Becauseofthesecurityreason,alotofbrowserdoesnotsupporttogetthefulllocalpathofthefile.
4.JavaFiletohandlerthebinaryfile
packagecom.sillycat.easytalker.controller;
importjava.io.IOException;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.log4j.Logger;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
publicclassFileController{
privatestaticfinalLoggerlogger=Logger.getLogger(FileController.class);
@RequestMapping("/fileupload.do")
publicvoiduploadFile(MultipartHttpServletRequestrequest,
HttpServletResponseresponse)throwsIOException{
MultipartFilemultipartFile=request.getFile("filemaps");
if(null!=multipartFile
&&null!=multipartFile.getOriginalFilename()){
logger.info("orginalfilename="
+multipartFile.getOriginalFilename());
//OutputStreamos=null;
//InputStreamis=null;
//try{
//is=multipartFile.getInputStream();
//Filefile=newFile("D:/"
//+multipartFile.getOriginalFilename());
//os=newFileOutputStream(file);
//
//byte[]b=newbyte[1024];
//intlen=0;
//while((len=is.read(b))!=-1){
//os.write(b,0,len);
//}
//}catch(Exceptione){
//logger.error("ErrorMessage:"+e);
//}finally{
//os.close();
//is.close();
//}
}
}
}
references:
http://www.phpletter.com/Our-Projects/AjaxFileUpload/
http://demos.telerik.com/aspnet-ajax/upload/examples/clientsidevalidation/defaultcs.aspx
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
http://hi.baidu.com/2012betterman/item/48d2592c2d79059db73263a9
http://www.cnblogs.com/zorroLiu/archive/2011/08/31/2160858.html
http://mzhou.me/?p=95250
相关推荐
为了美观,把 type="file" 控件隐藏。点击“上传”按钮,click调用隐藏文件控件,再选择文件。查了一遍,好像是ie为了安全控制,文件的必须鼠标点击过后,才能提交。还没有想到其他的方法。。。
5,success 提交成功后自动执行的处理函数,参数data就是服务器返回的数据。6,error 提交失败自动执行的处理函数。7,data 自定义参数。fileElementId: 'file1',