ajax上传图片,django后台接收

10 篇文章 0 订阅

之前没写过上传图片,现在两个项目都被我遇到了上传图片,上网找了好多,终于解决了。

我参考很多,但是其他网址找不到了,只记得这一个,参考:Ajax实现单图片上传,多图片上传,以及和对象的综合上传

接下来写一下我自己总结的代码(我是根据项目需求总结的,不需要照搬):

css不重要

.imagePreview {
  width: 200px;
  height: 180px;
  background-position: center center;
  /* background:url(http://cliquecities.com/assets/no-image-e3699ae23f866f6cbdf8ba2443ee5c4e.jpg); */
  background-color:#fff;
  background-size: cover;
  background-repeat:no-repeat;
  display: inline-block;
  box-shadow:0px -3px 6px 2px rgba(0,0,0,0.2);
}

.imgUp
{
  margin-bottom:15px;
}
.del
{
  position:absolute;
  top:0px;
  height:30px;
  text-align:center;
  line-height:30px;
  background-color:rgba(255,255,255,0.6);
  cursor:pointer;
  border: 0;
  left: 215px;
}
.imgAdd
{
  width:30px;
  height:30px;
  border-radius:50%;
  background-color:#4bd7ef;
  color:#fff;
  box-shadow:0px 0px 2px 1px rgba(0,0,0,0.2);
  text-align:center;
  line-height:30px;
  margin-top:0px;
  cursor:pointer;
  font-size:15px;
}

html(如果是submit应该直接提交就可以吧,我没试)

<!-- enctype="multipart/form-data"必须写 -->
<form id="knowAddForm" name="knowAddForm" enctype="multipart/form-data">
	<!-- {% csrf_token %} 因为不是直接submit,所以不用写,仅限django-->
	<input type="text" id="userId" name="userId" placeholder="">
	<div id='card-body-add' class="row mt-4">
		<div class="col-lg-4 imgUp">
			<div class="imagePreview"></div>
			<label class="btn btn-info" style="top: 6px;">Upload
				<!-- accept="image/gif,image/jpeg,image/jpg,image/png"只能选择图片 -->
				<!-- multiple 支持多张图片 -->
				<input type="file" name="imagesAdd" class="uploadFile_img_add" accept="image/gif,image/jpeg,image/jpg,image/png" style="width: 0px; height: 0px; overflow: hidden;" multiple>
			</label>
			<i class="fa fa-times del"></i>
		</div>
		<i class="fa fa-plus imgAdd"></i>
	</div>
	<button type="button" id="addOKButton">OK</button>
</form>

js添加或删除div(这是我自己项目需要,不用关注)

//添加div
$(".imgAdd").click(function(){
	count_add = $('#card-body-add .imgUp').length;
	if (count_add < 3) {
		$(this).closest(".row").find('.imgAdd').before('<div class="col-lg-4 imgUp"><div class="imagePreview"></div><label class="btn btn-info" style="top:6px;">Upload<input type="file"  name="imagesAdd" class="uploadFile_img_add" accept="image/gif,image/jpeg,image/jpg,image/png" style="width:0px;height:0px;overflow:hidden;" multiple></label><i class="fa fa-times del"></i></div>');
	}else{
			alert('最多可上传3张照片');
	}
});
//删除div
$(document).on("click", "i.del" , function() {
	$(this).parent().remove();
});

js选择的图片在页面显示

$(function() {
    $(document).on("change",".uploadFile_img_add", function(){
    	var uploadFile = $(this);
        var files = this.files ;
        if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
        if (/^image/.test( files[0].type)){
        	if (files[0].size >= 5242880){
          		 return  alert( '图片最大上传5MB。请重新选择');
          	}
          	
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){
				var image = new Image();
				image.height = 180;
				image.width = 200;
				image.title  = files.name;
				image.name  = "image_path_add";
				image.src    = this.result;
				uploadFile.closest(".imgUp").find('.imagePreview').empty();//确保div里最多放一张图片
				uploadFile.closest(".imgUp").find('.imagePreview').append(image);
            }
        }
    });
});

ajax上传图片(重要)

$('#addOKButton').click(function(){
	var formData=new FormData();
	
	//因为我需要多次上传多张照片,所以这样做(有好的建议可以提出来哦,我只会这种笨办法),普通的参照上面链接
	imgCount = $('.uploadFile_img_add').length
	
	//因为我最多能上传3张照片,所以做3次判断
	for (var i=0;i<imgCount;i++){
    	if(i == 0){
    		formData.append("imgFiles_add",$('.uploadFile_img_add')[0].files[0])
    	}
    	if(i == 1){
    		formData.append("imgFiles_add",$('.uploadFile_img_add')[1].files[0])
    	}
    	if(i == 2){
    		formData.append("imgFiles_add",$('.uploadFile_img_add')[2].files[0])
    	}
    }

    var userId=$("#knowAddForm #userId").val();
    formData.append("userId",userId);

	$.ajax({
		type: "POST",
	    url: '/user_add/',
        dataType:"json",
	    data:formData,
	    async: false,
        cache: false,
        contentType: false, //禁止设置请求类型
        processData: false, //禁止jquery对DAta数据的处理,默认会处理
	    headers: {
		    "X-CSRFToken": getCookie("csrftoken")
		},//python专用的可能是,具体方法如何写请参考之前的文章
        success: function (result) {
        	alert("成功");
        },
        error : function() {
            alert("error!"); 
        }
	});
});

django后台接收(重要)

from django.http import HttpResponse
import os.path
import shutil
from django.core.files.storage import FileSystemStorage

def knowledgeDetail_add(request):
    if request.method == 'POST':
    
		userId= request.POST.get('userId')
		#django接收前台传过来的照片
		image = request.FILES.getlist('imgFiles_add')
		
 		path_name = '/var/usr/images/'
		upload_img = []
		num = 1
		
		#shutil.rmtree函数可用于递归删除目录中包含的文件和子目录。
		if os.path.exists(path_name):
			shutil.rmtree(path_name)

		for i in range(0, len(image)):
			upload_img.append(image[i])

		#将图片写到指定路径下,并修改文件名称
		for f in upload_img:
			upload_img_name = 'img_' + str(userId) + '_'+ str(num) + '.jpg'
			file = FileSystemStorage(location= path_name)
			file_name = file.save(upload_img_name, f)
			image_file_path = image_file_path + path_name + upload_img_name + ';'
			num = num + 1

		return HttpResponse(image_file_path)

以上,如果有不对的地方,欢迎一起探讨

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用Ajax登录Django后台的示例。 前端代码: ``` <form id="login-form"> {% csrf_token %} <label for="username">用户名</label> <input type="text" id="username" name="username" required> <label for="password">密码</label> <input type="password" id="password" name="password" required> <button type="submit">登录</button> </form> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(function() { $('#login-form').submit(function(event) { event.preventDefault(); // 阻止表单的默认提交行为 // 获取表单数据 var username = $('#username').val(); var password = $('#password').val(); var csrfmiddlewaretoken = $('input[name="csrfmiddlewaretoken"]').val(); // 发送Ajax请求 $.ajax({ type: 'POST', url: '/login/', // Django后台登录视图的URL data: { username: username, password: password, csrfmiddlewaretoken: csrfmiddlewaretoken }, success: function(data) { if (data.success) { // 登录成功,跳转到首页 window.location.href = '/'; } else { // 登录失败,显示错误信息 alert(data.message); } }, error: function() { // 请求失败,显示错误信息 alert('请求失败,请稍后重试!'); } }); }); }); </script> ``` 后台代码: ``` from django.shortcuts import render from django.http import JsonResponse from django.contrib.auth import authenticate, login def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: # 登录成功 login(request, user) return JsonResponse({'success': True}) else: # 登录失败 return JsonResponse({'success': False, 'message': '用户名或密码错误!'}) else: # GET请求返回登录页面 return render(request, 'login.html') ``` 在上述代码中,前端使用jQuery库来发送Ajax请求,后台使用Django框架处理请求,并返回JSON格式的数据。在实际应用中,需要根据具体的业务逻辑来验证用户身份,并返回相应的数据。其中,`{% csrf_token %}`用于防止跨站请求伪造攻击。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值