一步操作:轻松实现ajax上传file到服务器 (ajax上传file到服务器)

随着互联网技术的不断发展,越来越多的网站需要实现文件上传功能,特别是一些图片或视频分享类网站。而针对文件上传的方式,为了提高用户体验和页面效果,越来越多的网站采用了ajax方式上传文件,从而实现了无刷新上传文件,同时还可以实现文件的实时预览功能。本文将介绍如何通过一步操作实现ajax上传file到服务器。

一、选择要上传的文件

上传之前,首先需要用户选择要上传的文件,这里我们采用html中的input标签来选择文件,具体实现如下:

“`html

“`

这里的name属性即为表单的名称,id属性可以用于标识该表单。

二、编写ajax上传的代码

为了实现ajax上传file到服务器,我们需要编写相应的ajax代码。在这里,我们可以使用jQuery库中的ajax方法来实现ajax上传。ajax方法与其他jQuery方法类似,都使用$.ajax()的语法,具体实现如下:

“`javascript

$(document).ready(function(){

$(“#myfile”).change(function(){

var formData = new FormData();

formData.append(‘myfile’, $(‘#myfile’)[0].files[0]);

$.ajax({

url: ‘upload.php’,

type: ‘POST’,

data: formData,

processData: false,

contentType: false,

success: function(data){

alert(data);

}

});

});

});

“`

上述代码中,我们在文件改变事件中,使用FormData对象来创建表单数据,然后将要上传的文件添加到表单数据中,最后通过ajax方法来实现文件的上传操作。其中,url参数是指上传到的PHP文件地址,type参数为POST方式提交,data参数即为表单数据,processData参数必须设置为false,否则会报错,contentType参数也必须设置为false,否则会出问题。最后在成功的回调函数中,输出上传结果。

三、编写上传文件的PHP脚本

通过ajax上传file到服务器之后,就需要编写相应的PHP脚本来接收上传的文件,并将上传的文件保存到指定的位置。在这里,我们可以采用PHP中的move_uploaded_file()方法来实现文件的保存,具体实现如下:

“`php

if($_FILES[‘myfile’][‘error’] > 0){

echo ‘上传失败’;

}else{

$file = $_FILES[‘myfile’][‘name’];

$path = ‘./uploads/’;

if(move_uploaded_file($_FILES[‘myfile’][‘tmp_name’],$path.$file)){

echo ‘上传成功’;

}else{

echo ‘上传失败’;

}

}

?>

“`

在PHP脚本中,我们首先判断上传是否成功,然后获取上传的文件名,指定上传文件的保存路径,最后通过move_uploaded_file()方法来实现文件的保存。

四、实现文件上传的进度条

为了提高用户体验和页面效果,我们可以使用ajax来实现文件上传进度的显示。jQuery库中提供了ajax的progress事件来实现文件上传进度的显示,具体实现如下:

“`javascript

$.ajax({

url: ‘upload.php’,

type: ‘POST’,

data: formData,

processData: false,

contentType: false,

xhr: function(){

var xhr = $.ajaxSettings.xhr();

xhr.upload.onprogress = function(evt){

var loaded = evt.loaded;

var total = evt.total;

var percent = loaded/total*100;

$(“progress”).attr(“value”, percent);

$(“#progress”).html(percent+’%’);

}

return xhr;

},

success: function(data){

alert(data);

}

});

“`

在ajax方法中,我们通过xhr参数来获取XMLHttpRequest对象,然后给XMLHttpRequest对象的upload属性添加onprogress事件来实现上传进度的显示。这里,我们通过计算已经上传的字节数和文件总字节数来实现文件上传进度的百分比,并将百分比输出到进度条标签中。

以上就是通过一步操作实现ajax上传file到服务器的全过程,通过这种方式上传文件,不仅可以实现无刷新上传文件功能,而且还可以实现实时上传进度的动态显示,是一种更加高效、方便的文件上传方式。

相关问题拓展阅读:

jsp中使用jquery的ajaxfileupload插件怎么实现异步上传

ajaxfileupload实现异步上传的完整例子:

P页面中引入的橡高script代码:

function ajaxFileUpload()

{

$(“#loading”).ajaxStart(function(){

$(this).show();

})//开始上传文件时显示一个图片

.ajaxComplete(function(){

$(this).hide();

});//文件上传完成将图片隐藏起来

$.ajaxFileUpload({

url:’AjaxImageUploadAction.action’,//用于文件上传的服务器端请求地址

secureuri:false,//一般设置为false

fileElementId:’imgfile’,//文件上传空间的id属性

dataType: ‘json’,//返回值类型 一般设置为json

success: function (data, status) //服务器成功响应处理函数

{

alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量

if(typeof(data.error) != ‘undefined’)

{

if(data.error != ”)

{

alert(data.error);

}else

{

alert(data.message);

}

}

},

error: function (data, status, e)//服务器响应失败处理函数

{

alert(e);

}

}

)

return false;

}

struts.xml配置文件中的配置方法:

text/html

text/html

上传处理的Action ImageUploadAction.action

package com.test.action;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.Arrays;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings(“serial”)

public class ImageUploadAction extends ActionSupport {

private File imgfile;

private String imgfileFileName;

private String imgfileFileContentType;

private String message = “你已成功上传文件”;

public File getImgfile() {

return imgfile;

}

public void setImgfile(File imgfile) {

this.imgfile = imgfile;

}

public String getImgfileFileName() {

return imgfileFileName;

}

public void setImgfileFileName(String imgfileFileName) {

this.imgfileFileName = imgfileFileName;

}

public String getImgfileFileContentType() {

return imgfileFileContentType;

}

public void setImgfileFileContentType(String imgfileFileContentType) {

this.imgfileFileContentType = imgfileFileContentType;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

@SuppressWarnings(“deprecation”)

public String execute() throws Exception {

String path = ServletActionContext.getRequest().getRealPath(“/upload/mri_img_upload”);

String imgTypes = new String { “gif”, “jpg”, “jpeg”, “png”,”bmp” };

try {

File f = this.getImgfile();

String fileExt = this.getImgfileFileName().substring(this.getImgfileFileName().lastIndexOf(“.”) + 1).toLowerCase();

/*

if(this.getImgfileFileName().endsWith(“.exe”)){

message=”上传的文件格式不允许!!!”;

return ERROR;

}*/

/**

* 检测上传文件的扩展名是否合法

* */

if (!Arrays. asList(imgTypes).contains(fileExt)) {

message=”只能上传 gif,jpg,jpeg,png,bmp等格式的文件!”;

return ERROR;

}

FileInputStream inputStream = new FileInputStream(f);

FileOutputStream outputStream = new FileOutputStream(path + “/”+ this.getImgfileFileName());

byte buf = new byte;

int length = 0;

while ((length = inputStream.read(buf)) != -1) {

outputStream.write(buf, 0, length);

}

inputStream.close();

outputStream.flush();

} catch (Exception e) {

e.printStackTrace();

message = “文件上传失败了!!!!”;

}

return SUCCESS;

}

}

<!– 执行上传文件操作的函数 —

<script type=text/javascript

function ajaxFileUpload(){

$.ajaxFileUpload({url:’update.do?method=uploader’, //需要链接到服务器地址

secureuri:false,

fileElementId:’houseMaps’, //文件选择框谈脊的id属性

dataType: ‘xml’,//服务器返回的格式,可以是json

success: function (data, status) //相当于java中try语句含岩渗块的用法{$(‘#result’).html(‘添加成功’);},

error: function (data, status, e) //相当于java中catch语句块的用法{$(‘#result’).html(‘添加失败枣脊’);}});}</script</head<body<form method=post action=update.do?method=uploader enctype=multipart/form-data

<input type=file id=houseMaps name=houseMaps/

<input type=button value=提交 onclick=ajaxFileUpload()/</form<div id=result</div</body</html服务器代码:

public class UpdateAction extends DispatchAction {

public ActionForward uploader(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

UpFormForm upFormForm = (UpFormForm) form;

FormFile ff = upFormForm.getHouseMaps();try {InputStream is = ff.getInputStream();

File file = new File(D:/ + ff.getFileName()); //指定文件存储的路径和文件名

OutputStream os = new FileOutputStream(file);

byte b = new byte;

int len = 0;

while((len = is.read(b)) != -1){

os.write(b, 0, len);}os.close();

is.close();

} catch (Exception e) {

返回列表

上一篇:高防主机是可以用吗

ajax上传file到服务器的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于ajax上传file到服务器,一步操作:轻松实现ajax上传file到服务器,jsp中使用jquery的ajaxfileupload插件怎么实现异步上传的信息别忘了在本站进行查找喔。


数据运维技术 » 一步操作:轻松实现ajax上传file到服务器 (ajax上传file到服务器)