jqueryajax上傳
㈠ jquery ajax上傳圖片問題
現在基本上沒有真正的AJAX圖片上傳,你想多了
都是偽AJAX上傳
但是如果是HTML5,倒是有可能,使html5的 canvas,可以把圖片序例化成base64字元串,把這個字元串傳到伺服器,處理一下,再保存就OK了,
我想知道你直接ajax怎麼傳,把你本地路徑傳過去嗎~~~~~
肯定是不行的
㈡ jQuery+ajax文件上傳失敗,什麼原因
大部分 都是超出了 伺服器的上傳大小限制
還有就是 ajax 上傳類型是否正確設置 ,類型轉換檢查錯誤沒,示例代碼:
var data = new FormData();
data.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'ajax.php',
data: data,
processData: false,
type: 'POST'
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data',
success: function (data) {
alert(data);
}
});
㈢ ajax jquery 中的 文件上傳問題(jsp+java開發)
試想,如果js就能上傳文件,是多麼可怕的事情。如果你登錄某個網站,這個網站把你的私密文件偷偷都上傳了,會是什麼結局?
所以瀏覽器,都要做到安全性考慮,是不會允許js來上傳文件的,那麼上傳文件 必須通過form表單來實現,並且必須通過表單的file文本框來實現,並且必須有用戶點擊選擇文件。
上傳文件的安全性處理,是有很深的用意的。
所以你要上傳文件,又不想動當前頁面的話,建議還是用iframe上傳吧。iframe裡面套一個form表單。
如果只是在pc網站上用的話,也可以考慮用flash插件、silverlight插件。
㈣ jquery不使用插件通過ajax方法上傳文件
傳統的表單也需要定義「multipart/form-data」這樣的方式,就是將文件轉成二進制流上傳到伺服器。而jquery的ajax本身貌似本身並沒有辦法讀取本地的文件形成二進制流上傳到伺服器。只能用插件來實現。
㈤ DWZ中怎樣整合JQuery的ajaxFileUpload上傳插件
jQuery插件AjaxFileUpload可以實現ajax文件上傳,需要jQuery庫文件和ajaxfileupload.js
一.引入部分
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
二.<body>部分
<img src="images/nophoto.jpg" id="picture" width="160px" height="200px"/>
<input type="file" id="touxiang" name="photo" size="10" onchange="changImg()"/>
注意:使用AjaxFileUpload插件上傳文件可不需要form
<form name="form" action="" method="POST" enctype="multipart/form-data">
……相關html代碼……
</form>
三.js部分
function changImg(){
$.ajaxFileUpload
(
{
url:'XXX.action', //上傳文件的服務端
secureuri:false, //是否啟用安全提交
dataType: 'text', //數據類型
fileElementId:'touxiang', //表示文件域ID
//提交成功後處理函數 html為返回值,status為執行的狀態
success: function(html,status)
{
},
//提交失敗處理函數
error: function (html,status,e)
{
}
}
)
}
四.原理
利用jQuery的選擇器獲得file文件上傳框中的文件路徑值,然後動態的創建一個iframe,並在裡面建立一個新的file 文件框,提供post方式提交到後台。最後,返回結果到前台。
五.總結
使用jQuery插件AjaxFileUpload實現無刷新上傳文件非常實用,由於其簡單易用,因些這個插件相比其它文件上傳插件使用人數最多,非常值得推薦。
㈥ 用jquery實現ajax 上傳圖片提交到PHP
好像不可以吧,瀏覽器為了安全不能用javascript讀取本地文件的
㈦ 如何通過jQuery的上傳插件ajaxFileUpload上傳文件給webservice
var
elementIds=["flag"];
//flag為id、name屬性名
$.ajaxFileUpload({
url:
'uploadAjax.htm',
type:
'post',
secureuri:
false,
//一般設置為false
fileElementId:
'file',
//
上傳文件的id、name屬性名
dataType:
'text',
//返回值類型,一般設置為json、application/json
elementIds:
elementIds,
//傳遞參數到伺服器
success:
function(data,
status){
alert(data);
},
error:
function(data,
status,
e){
alert(e);
}
});
㈧ jQuery+ajax文件上傳失敗,什麼原因
可能文件類型被限制,可能請求地址不匹配,可能文件大小被限制,可能伺服器端錯誤。。
你得把報錯信息發出來,不然沒法分析
㈨ 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"> </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頁面以後顯示的效果是:
㈩ 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;
}
}