実現したいこと
ajaxで画像ファイルをdjangoに送信し、ファイル形式をpng拡張子に変更してからエンコードをし、JSON形式で返し、png形式の画像をhtmlに表示したいです。
前提
ajaxでdjangoにファイルを送信して形式をpngに変更してからエンコード化してJSON形式で返したらresponseでエンコード化された物は表示できるのですが、それをデコードしてurlを表示するにはどうすればいいのでしょうか?エンコードのままでも画像の表示は可能と聞きましたが、そのままデータベースに保存することも可能なのでしょうか?
該当のソースコード
python
1 if request.method == 'POST' and request.FILES.get('profile_image'): 2 image = request.FILES.get('profile_image') 3 print(image) 4 # HEICファイルの場合のみ、変換処理を実行 5 if image.name.endswith('.heic') or image.name.endswith('.heif'): 6 # pyheifでHEICファイルを読み込み 7 heif_file = pyheif.read(image) 8 # PILで画像を読み込み 9 img = Image.frombytes(heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride) 10 # 画像をPNG形式で保存 11 img.save(image.name.replace('.heic', '.png'), 'PNG') 12 # 画像をbase64エンコード 13 with open(image.name.replace('.heic', '.png'), "rb") as image_file: 14 encoded_string = base64.b64encode(image_file.read()).decode("utf-8") 15 # base64エンコードした画像をJSON形式に変換 16 response_data = {'image': encoded_string} 17 response_json = json.dumps(response_data) 18 # JSON形式のデータを送信 19 return JsonResponse(response_json, safe=False)
js
1 // using jQuery 2function getCookie(name) { 3 var cookieValue = null; 4 if (document.cookie && document.cookie != '') { 5 var cookies = document.cookie.split(';'); 6 for (var i = 0; i < cookies.length; i++) { 7 var cookie = jQuery.trim(cookies[i]); 8 // Does this cookie string begin with the name we want? 9 if (cookie.substring(0, name.length + 1) == (name + '=')) { 10 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 11 break; 12 } 13 } 14 } 15 return cookieValue; 16} 17var csrftoken = getCookie('csrftoken'); 18 19$(function() { 20 $('#profile_image_button').on('click', function(){ 21 $('#profile_image').trigger("click"); 22 }) 23}); 24$(function() { 25 $('#profile_image').on('change', function() { 26 // image = $('#profile_image')[0].files[0]; 27 image = $('#profile_image')[0].files[0]; 28 console.log(image) 29 var formData = new FormData(); 30 formData.append('profile_image', image); 31 console.log(formData) 32 function csrfSafeMethod(method) { 33 // these HTTP methods do not require CSRF protection 34 return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 35 } 36 $.ajax({ 37 url: "{% url 'product:profile_modify' %}", 38 method: "POST", 39 processData:false, 40 contentType: false, 41 data: formData, 42 dataType: "json", 43 beforeSend: function(xhr, settings) { 44 if (!csrfSafeMethod(settings.type) && !this.crossDomain) { 45 xhr.setRequestHeader("X-CSRFToken", csrftoken); 46 } 47 }, 48 success:function(response) { 49 console.log(response); 50 console.log(response.image); 51 const image_url = response.image 52 $('#preview').attr('src', image_url); 53 $('#profile_image').attr('src', image_url); 54 } 55 }) 56 }); 57});
試したこと
デコードするためにJSON.loads(response)などを行いましたがJSON.loadsなんて関ないよと怒られてしまいました。ご回答よろしくお願いします。

あなたの回答
tips
プレビュー