使用 jquery ajax 上傳文件 (file upload using jquery ajax)


問題描述

使用 jquery ajax 上傳文件 (file upload using jquery ajax)

I want to upload a image with a description like:

data = '{"filename":"' + myfilename + '", "file":"' + file + '", "description":"' +
    description + '"}';

$.ajax({
    type: "POST",
    url: "filehandler.ashx",
    data: data,
    success: function (result) {
        alert(result);
    },
    error: function () {
        alert("There was error uploading file!");
    }
});

how can I do it? I can't read file as HttpPostedFile in generic handler. context.Request.Form also doesn't have any keys.

‑‑‑‑‑

參考解法

方法 1:

I'm sorry, If I not posted fully what I did in question. Anyway I got it to work.

var data = new FormData();

data.append("name", filename);
data.append("file", file);

In generic handler

HttpPostedFile file = context.Request.Files["file"];
string fileName = context.Request.Form["filename"];

Using FormData Objects

方法 2:

you cant post files with ajax you have to post it in a iframe to have the same result

this is what I did

var form = "#myform";
var url = "http://post.it/";
var iframeName = 'iframePost' + (new Date()).getTime(); 
$('<iframe id="'+iframeName+'" name="' + iframeName + '" style="display:none;"/>').appendTo('body');
$(form).attr('target',iframeName)
    .attr('action',url)
    .attr('enctype','multipart/form‑data')
    .append('<input type="hidden" name="_iframe" value="' + iframeName + '" />');
    form.submit();

to have a callback let the iframe return a script with something like 

window.parent.callBack(data);

(by DarshanaDarshanaEaterOfCode)

參考文件

  1. file upload using jquery ajax (CC BY‑SA 3.0/4.0)

#jquery #generic-handler #JSON #C#






相關問題

讓 jQuery 與 Netscape 7 和 8 一起工作 (Getting jQuery to work with Netscape 7 and 8)

使用 Jquery 的 mvc3 搜索結果 (mvc3 search results with Jquery)

從嵌套的 jquery 函數返回一個值 (Return a value from nested jquery function)

Mencocokkan lebar divisi dengan jquery (Matching division widths with jquery)

無法在 jQuery AJAX 中多次生成點擊事件 (unable to generate click event more than once in jQuery AJAX)

使用雙引號格式並用逗號分隔元素數組 (Implode an element array with double quote format and separated by comma)

選擇不更新 (Select doesn't update)

chrome中帶有省略號的多行文本問題 (issue with multiline text with ellipsis in chrome)

AJAX/PHP/JS - 無法將頁面內容加載到容器中 (AJAX/PHP/JS - Cannot load page content into container)

使用 jQuery 將文本插入 textarea (Insert text into textarea with jQuery)

滾動到頁面底部,僅當用戶在 DOM 操作之前已經位於底部時 (Scroll to bottom of page, only if the user already was at the bottom before DOM manipulation)

如何設置單選按鈕的樣式,使其看起來像普通的可點擊按鈕? (How do I style a radio button to look like a normal clickable button?)







留言討論