当前位置:首页 » 文件管理 » jqajax图片上传

jqajax图片上传

发布时间: 2022-09-12 02:51:49

A. ajax+jquery+ashx如何实现上传文件

第一:建立Default.aspx页面
<html>
<head runat="server">
<title>ajax图片上传</title>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.form.js" type="text/javascript"></script>

<script type="text/javascript">
function upload(){
var path = document.getElementById("File1").value;
var img = document.getElementById("img1");
if($.trim(path)==""){
alert("请选择要上传的文件");
return;
}

$("#form1").ajaxSubmit({
success: function (str) {
if(str!=null && str!="undefined"){
if (str == "1") {alert("上传成功");document.getElementById("img1").src="images/logo.jpg?"+new Date();/*上传后刷新图片*/}
else if(str=="2"){alert("只能上传jpg格式的图片");}
else if(str=="3"){alert("图片不能大于1M");}
else if(str=="4"){alert("请选择要上传的文件");}
else {alert('操作失败!');}
}
else alert('操作失败!');
},
error: function (error) {alert(error);},
url:'Handler.ashx', /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
dataType: "text" /*设置返回值类型为文本*/
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="File1" name="File1" type="file" />
<input id="iptUp" type="button" value="上传Logo" onclick="upload()"/>
<img id="img1" alt="网站Logo" src="images/weblogo.jpg" />
</form>
</body>
</html>

二、新建一个一般处理文件Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
HttpPostedFile _upfile = context.Request.Files["File1"];
if (_upfile == null)
{
ResponseWriteEnd(context, "4");//请选择要上传的文件
}
else
{
string fileName = _upfile.FileName;/*获取文件名: C:\Documents and Settings\Administrator\桌面\123.jpg*/
string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写: jpg*/
int bytes = _upfile.ContentLength;//获取文件的字节大小

if (suffix != "jpg")
ResponseWriteEnd(context, "2"); //只能上传JPG格式图片
if (bytes > 1024 * 1024)
ResponseWriteEnd(context, "3"); //图片不能大于1M

_upfile.SaveAs(HttpContext.Current.Server.MapPath("~/images/logo.jpg"));//保存图片
ResponseWriteEnd(context, "1"); //上传成功
}
}

private void ResponseWriteEnd(HttpContext context, string msg)
{
context.Response.Write(msg);
context.Response.End();
}

public bool IsReusable {
get {
return false;
}
}
}

您可以按照自己的需求来修改,希望对您有帮助!

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

JSP页面中引入的script代码
<script>
function
ajaxFileUpload()
{
$("#loading").ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来
$.ajaxFileUpload({
url:'AjaxImageUploadAction.action',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:'imgfile',//文件上传空间的id属性
<input
type="file"
id="imgfile"
name="file"
/>
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;
}
</script>
struts.xml配置文件中的配置方法:
<struts>
<package
name="struts2"
extends="json-default">
<action
name="AjaxImageUploadAction"
class="com.test.action.ImageUploadAction">
<result
type="json"
name="success">
<param
name="contentType">text/html</param>
</result>
<result
type="json"
name="error">
<param
name="contentType">text/html</param>
</result>
</action>
</package>
</struts>
上传处理的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.<String>
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[1024];
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;
}
}
转载,仅供参考。

C. jqueryajax不能上传图片

不能上传的原因可能是jquery插件使用不正确。

解决方法:

1、在head之间加入jquery引用

<scripttype="text/javascript" src="jquery.js"></script>

<scriptsrc="project/js/jquery.form.js" type="text/javascript"></script>

<scriptsrc="project/js/fileload.js" type="text/javascript"></script>

2、定义fileload.js,代码如下:

function createHtml(obj) {
var htmstr = [];
htmstr.push( "<form id='_fileForm' enctype='multipart/form-data'>");
htmstr.push( "<table cellspacing="0" cellpadding="3" style="margin:0 auto; margin-top:20px;">");
htmstr.push( "<tr>");
htmstr.push( "<td class="tdt tdl">请选择文件:</td>");
htmstr.push( "<td class="tdt tdl"><input id="loadcontrol" type="file" name="filepath" id="filepath" /></td>");
htmstr.push( "<td class="tdt tdl tdr"><input type="button" onclick="fileloadon()" value="上传"/></td>");
htmstr.push( "</tr>");
htmstr.push( "<tr> <td class="tdt tdl tdr" colspan='3'style='text-align:center;'><div id="msg">&nbsp;</div></td> </tr>");
htmstr.push( "<tr> <td class="tdt tdl tdr" style=" vertical-align:middle;">图片预览:</td> <td class="tdt tdl tdr" colspan="2"><div style="text-align:center;"><img src="project/Images/NoPhoto.jpg"/></div></td> </tr>");
htmstr.push( "</table>")
htmstr.push( "</form>");
obj.html(htmstr.join(""));
}

function fileloadon() {
$("#msg").html("");
$("img").attr({ "src": "project/Images/processing.gif" });
$("#_fileForm").submit(function () {
$("#_fileForm").ajaxSubmit({
type: "post",
url: "project/help.aspx",
success: function (data1) {
var remsg = data1.split("|");
var name = remsg[1].split("/");
if (remsg[0] == "1") {
var type = name[4].substring(name[4].indexOf("."), name[4].length);
$("#msg").html("文件名:" + name[name.length - 1] + " --- " + remsg[2]);
switch (type) {
case ".jpg":
case ".jpeg":
case ".gif":
case ".bmp":
case ".png":
$("img").attr({ "src": remsg[1] });
break;
default:
$("img").attr({ "src": "project/Images/msg_ok.png" });
break;
}
} else {
$("#msg").html("文件上传失败:" + remsg[2]);
$("img").attr({ "src": "project/Images/msg_error.png" });
}
},
error: function (msg) {
alert("文件上传失败");
}
});
return false;
});
$("#_fileForm").submit();
}

3、服务端处理上传。

protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpPostedFile postFile = Request.Files[0];
//开始上传
string _savedFileResult = UpLoadFile(postFile);
Response.Write(_savedFileResult);

}
catch(Exception ex)
{
Response.Write("0|error|上传提交出错");
}

}
public string UpLoadFile(HttpPostedFile str)
{
return UpLoadFile(str, "/UpLoadFile/");
}
public string UpLoadFile(HttpPostedFile httpFile, string toFilePath)
{
try
{
//获取要保存的文件信息
string filerealname = httpFile.FileName;
//获得文件扩展名
string fileNameExt = System.IO.Path.GetExtension(filerealname);
if (CheckFileExt(fileNameExt))
{
//检查保存的路径 是否有/结尾
if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

//按日期归类保存
string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
if (true)
{
toFilePath += datePath;
}

//物理完整路径
string toFileFullPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + toFilePath;

//检查是否有该路径 没有就创建
if (!System.IO.Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}

//得到服务器文件保存路径
string toFile = Server.MapPath("~" + toFilePath);
string f_file = getName(filerealname);
//将文件保存至服务器
httpFile.SaveAs(toFile + f_file);
return "1|" + toFilePath + f_file + "|" + "文件上传成功";
}
else
{
return "0|errorfile|" + "文件不合法";
}
}
catch (Exception e)
{
return "0|errorfile|" + "文件上传失败,错误原因:" + e.Message;
}
}

/// <summary>
/// 获取文件名
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
private string getName(string fileNamePath)
{
string[] name = fileNamePath.Split('\');
return name[name.Length - 1];
}
/// <summary>
/// 检查是否为合法的上传文件
/// </summary>
/// <param name="_fileExt"></param>
/// <returns></returns>
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".rar",".png" };
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;

}

public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("HHmmss"));
serial.Append(rd.Next(100, 999).ToString());
return serial.ToString();
}

4、运行defualt.aspx页面以后显示的效果是:

D. 谁能给一个jquery或者js的 ajax图片上传例子

自己写比较复杂哦、原则上来说、文件是不能进行ajax上传的、一般是创建了个iframe,然后上传文件,做成了ajax的效果。
我是建议你用插件吧、swfupload还算简单呀、

E. jquery如何将页面生成的图片上传到服务器

File Upload组件啊,是同步还是异步呢
html部分:
<input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="image/*">
文件引入:
<link rel="stylesheet" type="text/css" href="diyUpload/css/diyUpload.css"><script type="text/javascript" src="diyUpload/js/diyUpload.js"></script>
HTML部分:
<div id="demo"> <div id="as" ></div></div>
JS部分:
<script type="text/javascript">
/** 服务器地址,成功返回,失败返回参数格式依照jquery.ajax习惯;* 其他参数同WebUploader*/
$('#as').diyUpload({
url:'server/fileupload.php',
success:function( data ) {
console.info( data ); },
error:function( err ) {
console.info( err );
},
buttonText : '选择文件', chunked:true, // 分片大小
chunkSize:512 * 1024, //最大上传的文件数量, 总文件大小,单个文件大小(单位字节);
fileNumLimit:50,
fileSizeLimit:500000 * 1024,
fileSingleSizeLimit:50000 * 1024,
accept: {}});
</script>

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

ajaxfileupload实现异步上传的完整例子:
JSP页面中引入的script代码:
<script>
function ajaxFileUpload()
{
$("#loading").ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来

$.ajaxFileUpload({
url:'AjaxImageUploadAction.action',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:'imgfile',//文件上传空间的id属性 <input type="file" id="imgfile" name="file" />
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;
}
</script>
struts.xml配置文件中的配置方法:
<struts>
<package name="struts2" extends="json-default">
<action name="AjaxImageUploadAction" class="com.test.action.ImageUploadAction">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
<result type="json" name="error">
<param name="contentType">text/html</param>
</result>
</action>
</package>
</struts>
上传处理的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.<String> 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[1024];
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;
}
}

G. img如何接收jquery ajax异步上传的动态图片

你的表述没看懂,jquery 异步上传过后获取路径 直接给img 的src赋值不就完了?

H. 用jqueryajax实现点击图片提交form问题,怎么解决

给图片加个ID属性 如: <img src="" id="img_id"/>
$("#img_id").click(function(){
$.ajax({
type:'POST',
url:"love.php",
data:'id='+id,
success:function(data){
love.html(data);
love.fadeIn(300);
}
});
})
异步提交

I. jquery ajax 上传文件怎么搞

Query Ajax在web应用开发中很常用,它主要包括有ajax,get,post,load,getscript等等这几种常用无刷新操作方法,接下来通过本文给大家介绍jquery ajax 上传文件处理方式。
FormData对象
XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个”表单”.比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.
所有主流浏览器的较新版本都已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。之前都是用原生js的XMLHttpRequest写的请求
XMLHttpRequest方式
xhr.open("POST", uri, true);

xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);

其实jquery的ajax也可以支持到的,关键是设置:processData 和 contentType 。
ajax方式

var formData = new FormData();
var name = $("input").val();
formData.append("file",$("#upload")[0].files[0]);
formData.append("name",name);
$.ajax({
url : Url,
type : 'POST',
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(responseStr) {
if(responseStr.status===0){
console.log("成功"+responseStr);
}else{
console.log("失败");
}
},
error : function(responseStr) {
console.log("error");
}
});

J. jquery ajax上传图片问题

现在基本上没有真正的AJAX图片上传,你想多了
都是伪AJAX上传
但是如果是HTML5,倒是有可能,使html5的 canvas,可以把图片序例化成base64字符串,把这个字符串传到服务器,处理一下,再保存就OK了,

我想知道你直接ajax怎么传,把你本地路径传过去吗~~~~~
肯定是不行的

热点内容
公网ipftp访问 发布:2024-10-11 08:25:58 浏览:944
新款密码箱怎么改密码 发布:2024-10-11 08:25:15 浏览:980
静态ip访问不了xp服务器 发布:2024-10-11 08:19:23 浏览:293
excel编译 发布:2024-10-11 08:18:37 浏览:812
安卓手机如何保存q闪图 发布:2024-10-11 07:57:09 浏览:646
安卓怎么设置wifi的dns 发布:2024-10-11 07:57:08 浏览:598
androidlua脚本 发布:2024-10-11 07:52:17 浏览:392
kele55文件夹 发布:2024-10-11 07:52:15 浏览:760
xp怎么看wifi密码是多少 发布:2024-10-11 07:51:42 浏览:294
搭建阿里企业私有云服务器 发布:2024-10-11 07:43:53 浏览:285