當前位置:首頁 » 文件管理 » 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怎麼傳,把你本地路徑傳過去嗎~~~~~
肯定是不行的

熱點內容
同配置的汽油車和混動哪個貴 發布:2024-10-11 09:13:18 瀏覽:330
c語言程序設計案例教程答案 發布:2024-10-11 09:11:09 瀏覽:624
教學管理資料庫設計 發布:2024-10-11 09:02:44 瀏覽:274
a站視頻緩存不了 發布:2024-10-11 09:02:37 瀏覽:886
python文件名去掉後綴 發布:2024-10-11 08:57:59 瀏覽:614
公網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 瀏覽:816
安卓手機如何保存q閃圖 發布:2024-10-11 07:57:09 瀏覽:646