jQuery文件上传和ajax

时间:2015-11-25 21:06:21

标签: javascript php jquery ajax

所以,我有以下表格和js / php:

PHP

function UploadImage(e)
{
jQuery('#fileupload').fileupload({
    url: upload_image.ajax_url,
});

if(jQuery('#fileupload')) {
    var form = document.forms.namedItem("upload_video"); 
    var formdata = new FormData(form); 
    formdata.append('action', 'UploadImage');
    jQuery.ajax({           
        success : function(data){                   
                alert('sddsf');
            }
    })
}
};

JS

Imports System
Imports System.Web
Imports System.IO

Public Class Handler1
Implements System.Web.IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

    Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
    Dim savepath As String = ""
    Dim tempPath As String = ""

    tempPath = "Uploads" 'comment: this is the path where the file is uploaded'
    savepath = context.Server.MapPath(tempPath)
    Dim filename As String = postedFile.FileName

    If Not Directory.Exists(savepath) Then
        Directory.CreateDirectory(savepath)
    End If

    postedFile.SaveAs((savepath & "\") + filename)
    context.Response.Write((tempPath & "/") + filename)
    context.Response.StatusCode = 200
End Sub

ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
End Property

End Class

从这里可以看到,当使用Blueimp jQuery File upload(未正确编写js)选择图像时,我希望图像文件由php函数处理。

换句话说,js没有正确编写,我不知道如何启动插件然后当选择图像时,它由php函数通过ajax处理(意思是,我如何解析文件信息到php函数通过ajax?)

1 个答案:

答案 0 :(得分:1)

请勿直接使用$.ajax。该插件已在幕后完成。

这是一个基于代码的工作示例,但适用于在JSFiddle上运行:

$(document).ready(function(){
    var url = '/echo/json/';
    var formdata = {json: JSON.stringify({field1: 'value1'})};

    jQuery('#fileupload').fileupload({
        url: url,
        formData : formdata,        
        dataType: 'json',
        type: "POST",
        contentType:false,
        processData:false,
        success : function(data){                   
            alert('success...');
            console.dir(data);
        }
    });       
});

演示:http://jsfiddle.net/pottersky/8usb1sn3/3/