ajax将前端上传的图片传至后端并保存到当前项目路径

利用ajax将前端上传的图片传至后端并保存到当前项目路径(Django项目)

1.对应的HTML代码

<button type="button" id="upload">预测</button>
<p>result: <span id='result'></span></p>
<div style="position: absolute;top: 20%;left: 15%">
    <a href=":javascript" class="file"><input type="file"  name="file" id="Images" multiple="multiple"   accept="image/*" />点击这里上传图片
    </a>
	<div id="picViewsBox" style="width: 500px;height: 500px;color: #747171;border: 1px solid #8b8a8a;"><p style="text-align: center;margin-top: 50%">选择想要预测的图片</p></div>
</div>

2.对应的js代码

  //利用ajax获取上传图片信息,而且不刷新当前页面
        $(document).ready(function () {
//jq的处理函数,当点击提交按钮时执行。
            $("#upload").click(function () {
                var data = new FormData();
                var len = $('#Images')[0].files.length;
                for(var i =0;i<len;i++) {
                    var file = $('#Images')[0].files[i];
                    data.append('files', file);//将图片信息file保存到该对象
                };

                if (len==0){
                    alert("未上传图片!");
                }
                else {
                $.ajax({
                       url:'http://127.0.0.1:8000/get_picture_message/',
                       type:'POST',
                       data:data,
                       processData:false,//建议添加,否则值传可能不到对应url
                       contentType:false,//建议添加,否则值可能传不到对应url
                       success:function(arg){
                           console.log(arg);
                         $('#result').html(arg)
                       },
                       error:function(arg){
                         console.log(arg);
                         $('#result').html(arg);
                          alert("失败")
                       }
                     });

                }

            });

        });

3.后端代码

import os
from Rock_Intelligence_analysis import settings
from django.http import HttpResponse
def get_picture_message(request):
    if request.method == 'POST':
        files = request.FILES.getlist('files')#获取ajax传过来的myfiles值,类型为list
        #遍历list对象files,当选择多张图片时实现遍历保存图片
        for f in files:
            print(f.name)
            img_name = f'{f.name}'  # 重命图片名及格式
            print("名称:",img_name)
            img_path = os.path.join(settings.IMG_UPLOAD, img_name)  #设置图片保存的路径,settings.IMG_UPLOAD为settings.py中的属性,该属性需要自行设置
            print(img_path)
            #url = "..\static\picture\\" + img_name
            with open(img_path, 'ab') as fp:
                for chunk in f.chunks():
                    fp.write(chunk)
                fp.close()

        return HttpResponse("OK!")
    else:
        return HttpResponse("NOT OK!")

其中的settings.IMG_UPLOAD代码段,本人的路径是这个,其中BASE_DIR是项目的路径(setting.py中会自带有),'static/picture’为项目下面的文件夹(可根据自身要求设置),前提是static先要设置成静态路径。

IMG_UPLOAD=os.path.join(BASE_DIR,'static/picture')
  • 3
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值