首页编程java编程ajax上传文件?java上传下载文件

ajax上传文件?java上传下载文件

编程之家2026-05-251004次浏览

大家好,今天来为大家解答ajax上传文件这个问题的一些问题点,包括java上传下载文件也一样很多人还不知道,因此呢,今天就来为大家分析分析,现在让我们一起来看看吧!如果解决了您的问题,还望您关注下本站哦,谢谢~

ajax上传文件?java上传下载文件

怎么用ajax实现上传文件的功能

HTTP File Server

http-file-server是用 python实现的 HTTP文件服务器,支持上传和下载文件。

运行

$ python file-server.py files 8001

其中第一个参数files是存放文件的路径,第二个参数8001是 HTTP服务器端口。

接口

ajax上传文件?java上传下载文件

1.读取文件

GET/pathtofile/filename

2.读取文件夹下所有文件(已经忽略隐藏文件)

GET/path

返回文件列表为JSON数组,文件名末尾带有/的表示是文件夹。filename为文件名,mtime为修改时间。

[{"filename":"f1.txt","mtime":1001},{"filename":"p3/","mtime":1002}]

ajax上传文件?java上传下载文件

3.上传文件

采用POST方式上传文件,URL参数中传参数name表示上传的文件名,POST内容为文件内容。

POST/upload?name=filename

ajax示例:

// file is a FileReader object

var data= file.readAsArrayBuffer();

var xhr= new XMLHttpRequest();

var url="";

xhr.open("post", url, true);

xhr.setRequestHeader("Accept","application/json, text/javascript,*/*; q=0.01");

xhr.onreadystatechange= function(){

if(xhr.readyState==4&& xhr.status==200)

{

console.log(xhr.responseText);

}

}

xhr.send(data);

文件名 filename可以包含相对路径。比如:upload?name=md/xxx.md。则上传至md目录下。

如何用Ajax实现多文件上传

jquery实现多个上传文件教程:

首先创建解决方案,添加jquery的js和一些资源文件(如图片和进度条显示等):

1

2

3

4

5

jquery-1.3.2.min.js

jquery.uploadify.v2.1.0.js

jquery.uploadify.v2.1.0.min.js

swfobject.js

uploadify.css

1、页面的基本代码如下

这里用的是aspx页面(html也是也可的)

页面中引入的js和js函数如下:

1

2

3

4

5

6

7

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>

<script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"></script>

<script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>

<script src="js/swfobject.js" type="text/javascript"></script>

<link rel="external nofollow" href="css/uploadify.css" rel="stylesheet" type="text/css"/>

</script>

js函数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<script type="text/javascript">

$(document).ready(function(){

$("#uploadify").uploadify({

'uploader':'image/uploadify.swf',//uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框

'script':'Handler1.ashx',// script:后台处理程序的相对路径

'cancelImg':'image/cancel.png',

'buttenText':'请选择文件',//浏览按钮的文本,默认值:BROWSE。

'sizeLimit':999999999,//文件大小显示

'floder':'Uploader',//上传文件存放的目录

'queueID':'fileQueue',//文件队列的ID,该ID与存放文件队列的div的ID一致

'queueSizeLimit': 120,//上传文件个数限制

'progressData':'speed',//上传速度显示

'auto': false,//是否自动上传

'multi': true,//是否多文件上传

//'onSelect': function(e, queueId, fileObj){

// alert("唯一标识:"+ queueId+"\r\n"+

//"文件名:"+ fileObj.name+"\r\n"+

//"文件大小:"+ fileObj.size+"\r\n"+

//"创建时间:"+ fileObj.creationDate+"\r\n"+

//"最后修改时间:"+ fileObj.modificationDate+"\r\n"+

//"文件类型:"+ fileObj.type);

//}

'onQueueComplete': function(queueData){

alert("文件上传成功!");

return;

}

});

});

页面中的控件代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

<body>

<form id="form1" runat="server">

<div id="fileQueue">

</div>

<div>

<p>

<input type="file" name="uploadify" id="uploadify"/>

<input id="Button1" type="button" value="上传" onclick="javascript:$('#uploadify').uploadifyUpload()"/>

<input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadifyClearQueue()"/>

</p>

</div>

</form>

</body>

函数主要参数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$(document).ready(function(){

$('#fileInput1').fileUpload({

'uploader':'uploader.swf',//不多讲了

'script':'/AjaxByJQuery/file.do',//处理Action

'cancelImg':'cancel.png',

'folder':'',//服务端默认保存路径

'scriptData':{'methed':'uploadFile','arg1','value1'},

//向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"]

'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下

//'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子

'multi':'true',//多文件上传开关

'fileExt':'*.xls;*.csv',//文件过滤器

'fileDesc':'.xls',//文件过滤器详解见文档

'onComplete': function(event,queueID,file,serverData,data){

//serverData为服务器端返回的字符串值

alert(serverData);

}

});

});

后台一般处理文件:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

using System;

using System.Collections.Generic;

using System.Linq;

using System.IO;

using System.Net;

using System.Web;

using System.Web.Services;

namespace fupload

{

///<summary>

/// Handler1的摘要说明

///</summary>

public class Handler1: IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType="text/plain";

HttpPostedFile file= context.Request.Files["Filedata"];//对客户端文件的访问

string uploadPath= HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";//服务器端文件保存路径

if(file!= null)

{

if(!Directory.Exists(uploadPath))

{

Directory.CreateDirectory(uploadPath);//创建服务端文件夹

}

file.SaveAs(uploadPath+ file.FileName);//保存文件

context.Response.Write("上传成功");

}

else

{

context.Response.Write("0");

}

}

public bool IsReusable

{

get

{

return false;

}

}

}

}

以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。

ajax+html轻松实现文件上传有哪些步骤

这次给大家带来ajax+html轻松实现文件上传有哪些步骤,ajax+html轻松实现文件上传的注意事项有哪些,下面就是实战案例,一起来看一下。

引语:大家都知道,html中上传文件就一个input,type=file就搞定了。但是,这个标签的样式,实在不值得提点什么,要改动他的样式,恐怕也是较难的。但是其实挺简单,今天就来说说上传文件小技巧吧!

1.怎样自定义样式?

1)、只管按照自己喜欢看到的样式去定义即可,如<a href='javascript:;' class='upload-button'></a>,可以是背景图片效果,可以是文字指示,总之想怎么改怎么改!有了按钮,还需要一个文件名容器,用来存放选择上传文件时的名字,从而不让上传看起来枯涩难懂。

2)、添加真正需要上传的文件控件,并设置属性display:none;如<input type='file' class='hide'/>,这样就有了真正的上传文件的地方了。所以,可以说,上传文件的界面有多漂亮取决你的想象力!

2.怎样触发事件?

这是个重点,触发的点应该是自己写的样式处,而真正起作用的元素却是隐藏的,但是并不影响它的点击效果,只需要给它触发一个点击事件即可,如$('#target-file').trigger('click');

3.多选文件?

多文件上传,只需使用html的一个file的multiple=true即可,当然你也可以选择第三方的上传控件,如swfupload,效果是真心不错的,但是对于不想用的插件的人,就不起作用了。

4.相关插件?

界面美化其实可以使用jqueryui等插件;

要做一些友好的交互的话,都会用到ajax技术,无刷新切换、异步上传、提交,最后,其实ajax的路径也是可以保留的,使用pushState, replaceState实现 pjax.

表单验证:validform.js

异步提交文件: jquery.form.js

友好的弹窗提示:layer.js

5.一点兼容性的问题?

做界面方面的工作,最怕的也是很重要的工作,就是各个浏览器之间的兼容性问题,下面主要列几点供参考:

table宽度的处理方式不一致;

select, input显示高度不一致;

alert弹窗不一致;

...

6.演示代码

<a rel="external nofollow" rel="external nofollow" href="javascript:;" up-type-id="1" class="btn btn-default small-btn switch-upload-method"><span>本地上传</span></a>

<a rel="external nofollow" rel="external nofollow" href="javascript:;" up-type-id="2" class="upload-file-instead btn btn-default small-btn switch-upload-method"><span>打包工具</span></a>

<input type="file" name="apkFiles[]" id="local-upload-real-file" class="upload-file-real hide" response-id="local-upload-container" multiple='true'/>

<input type="file" name="apkToolFiles[]" id="apk-tool-real-file" class="upload-file-real hide" response-id="apk-tool-container-textarea"/>

<script>

$(function(){

var alertTitle='系统提示:';

var submitId='#do-submit';

$('#taskForm').Validform({

btnSubmit: submitId,

tiptype: 1,

ignoreHidden: true,

dragonfly: false,

tipSweep: true,

label:".label",

showAllError: false,

postonce: true,

ajaxPost: true,

datatype:{

},

beforeCheck:function(curform){

},

beforeSubmit:function(curform){

$('.upload-file-real').attr('disabled','disabled');

$(submitId).attr('disabled','disabled');//提交前禁用按钮

ajaxSubmitForm(curform);

$(submitId).removeAttr('disabled');//失败后恢复可提交

return false;

},

submitForm: function(){}//不再起作用

});

//切换上传方法

$('.switch-upload-method').off().on('click', function(){

//$(submitId).attr('disabled','disabled');

var pObj=$(this).parent().find('.switch-upload-method');

var index= pObj.index(this);

var uploadTypeId=$('#upload-type-id').val();//上传方式:1:打包工具;2:本地上传,0:没有上传方式

var uploadType=$(this).attr('up-type-id');

if(parseInt($('#sub-channel-count').html())> 0){

if(uploadTypeId!= uploadType){

layer.alert('还有子渠道包数据,不能完成切换,请先确认清除再切换!');

return false;

}

}

pObj.not(':eq('+ index+')').removeClass('btn-danger').addClass('btn-default');

pObj.eq(index).removeClass('btn-default').addClass('btn-danger');

if(uploadType== 36){//local-upload

$('#upload-type-id').val(uploadType);

$('#init-apk-container').show();

$('#apk-tool-container').hide();

$('#upload-main-control').find('.del-it-main').css({display:'inline-block'});

$('#local-upload-real-file').trigger('click');

}else if(uploadType== 35){//apk-tool

$('#upload-type-id').val(uploadType);

$('#init-apk-container').hide();

$('#local-upload-container').hide();

$('#upload-main-control').find('.del-it-main').hide();

$('#apk-tool-container').show();

}

});

//本地上传

$('#local-upload-real-file').off().on('change', function(){

if(!$(this).val()){

return false;

}

file_size= 0;

filepath=$(this).val();

maxFileSize= 30* 1024* 1024;

var browserCfg={};

var ua= window.navigator.userAgent;

if(ua.indexOf("MSIE")>=1){

browserCfg.ie= true;

}else if(ua.indexOf("Firefox")>=1){

browserCfg.firefox= true;

}else if(ua.indexOf("Chrome")>=1){

browserCfg.chrome= true;

}

if(browserCfg.ie){

var img= new Image();

img.src= filepath;

file_size= img.fileSize;

while(true){

if(img.fileSize> 0){

if(img.fileSize> maxFileSize){

alert("上传包超过30MB限制,请使用打包工具上传!");

return false;

}

break;

}

}

} else{

file_size= this.files[0].size;

if(file_size> maxFileSize){

alert("上传包超过30MB限制,请使用打包工具上传!");

return false;

}

}

var responseObjId=$(this).attr('response-id');

var responseObj=$('#'+ responseObjId);

$('#taskForm').ajaxSubmit({

url:'/aa/bb/uploadTmpApk',

resetForm: false,

dataType:'json',

beforeSubmit: function(option){

window.loading= layer.load(2);

},

success: function(data, statusText){

layer.close(window.loading);

if(data.status== 1){

$('#version-identifier').val(data.version);

responseObj.html(data.apkInfoHtml);

responseObj.show();

var delObj=$('#upload-main-control').find('.del-it-main');

delObj.css({'display':'inline-block'});

$('#sub-channel-count').html(data.apkTotal);

$('#init-apk-container').hide();

$(submitId).removeAttr('disabled');

}else{

layer.alert(data.info,{title: alertTitle});

}

},

error: function(data){

layer.close(window.loading);

layer.alert('未知错误,请稍后再试!');

}

});

return false;//防止dialog自动关闭

});

//打包工具

$('#apk-tool-real-file').off().on('change', function(){

if(!$(this).val()){

return false;

}

var responseObjId=$(this).attr('response-id');

var responseObj=$('#'+ responseObjId);

$('#Form').ajaxSubmit({

url:'/aa/bb/uploadTmpApkTool',

resetForm: false,

dataType:'json',

beforeSubmit: function(option){

window.loading= layer.load(2);

},

success: function(data, statusText){

layer.close(window.loading);

if(data.status== 1){

$('#version-identifier').val(data.version);

responseObj.html(data.infoHtml);

var parentContainer= responseObj.parent().parent(),

nameContainer= parentContainer.find('.apk-name-container'),

delObj= parentContainer.find('.del-it-apk-tool');

nameContainer.html(data.apkName);

nameContainer.attr('title', data.apkName);

$('#apk-tool-file-tmp').html(data.fileInfo);

$(submitId).removeAttr('disabled');

}else{

layer.alert(data.info,{title: alertTitle});

}

},

error: function(data){

layer.close(window.loading);

layer.alert('未知错误,请稍后再试!');

}

});

return false;//防止dialog自动关闭

});

$('.apk-tool-upload-button').on('click', function(){

$('#apk-tool-real-file').trigger('click');

});

});

</script>以上,主要就是,使用隐藏的input file标签选择,选择文件之后立即ajax提交,最后,整个表单ajax提交的过程。

合理使用一些css, js,让你的网页更自由!

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

Ajax()与后台交互使用详解

处理WebService跨域问题方法详解

关于ajax上传文件到此分享完毕,希望能帮助到您。

java能干嘛?java 网站数据库应用技术(大数据技术架构)