2017-09-22 33 views
0

javascript ajax関数を使用して画像データをサーバ(Djangoアプリ)に送信するにはどうすればいいですか?Ajaxを使用して画像を送信するには

以下は私のコードです。

// Get filename of image 
jsondata = JSON.parse(data); 
image_file_name = jsondata.fileurl; 
// document.getElementById('previewimage').src = image_file; 
// I can show the image. 

b64_image = btoa(unescape(encodeURIComponent(image_file))); 
var credentials = { 
    filename: image_file_name, 
    image: b64_image, 
}; 

// Send ajax request to the server 
$.ajax({ 
    url: HOST_NAME + "user/api/file_uploader/", 
    type: 'GET', 
    dataType: 'json', 
    data: credentials, 
    timeout: 10000, 
}) 
.done(function (data) { 

    // Get the result 
    jsondata = JSON.parse(data); 
    alert("File upload completed..."); 

}) 
// If false... 
.fail(function (XMLHttpRequest, textStatus, errorThrown) { 
    console.log("Upload error"); 
}) 
+2

コンテンツを送信する場合は、サーバーからデータを回復する場合にのみGETが有用であるため、GET要求ではなくPOST要求を使用する必要があります。 – Driblou

+0

アドバイスありがとうございます。しかし、私がPUTメソッドを使っても、リクエストはサーバーAPIに到達できませんでした。 –

+0

@KazzzStudio - Ehhrm、PUT!= GET – enhzflep

答えて

2

ajaxを使用してファイルを投稿するには、FromDataを使用する必要があります。

var form = $('form')[0]; 
var formData = new FormData(form); 

$.ajax({ 
    url: "ajax_php_file.php", // Url to which the request is send 
    type: "POST",    // Type of request to be send, called as method 
    data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
    contentType: false,  // The content type used when sending data to the server. 
    cache: false,    // To unable request pages to be cached 
    processData:false,  // To send DOMDocument or non processed data file it is set to false 
    success: function(data) // A function to be called if request succeeds 
    { 
    // success code . 
    } 
}); 
+0

アドバイスありがとうございます。しかし、私はイメージを取得するためにフォームを使用しません。私は私の電話カメラから画像を取得します。 FormDataはどのように使用できますか? –

1

コードに変更を加えるだけで済みます。

// Send ajax request to the server 
$.ajax({ 
    url: HOST_NAME + "user/api/file_uploader/", 
    type: 'POST',  // changed from GET to POST 
    dataType: 'json', 
    data: credentials, 
    timeout: 10000, 
    }) 
.done(function (data) { 
    // Get the result 
}) 
.fail(function (XMLHttpRequest, textStatus, errorThrown) { 
    console.log("Upload error"); 
}) 

としてGETを使用して作成します。 request methodsについて詳しく読むことができます。

関連する問題