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')
在ASP.NET MVC项目中,前端通常使用HTML5的`input[type=file]`元素让用户选择文件,然后通过JavaScript将选中的文件路径发送给服务器。以下是前端的基本步骤: HTML部分: ```html <input type="file" id="fileInput" /> <button onclick="uploadFile()">上传</button> <div id="filePath"></div> ``` JavaScript部分(假设使用jQuery): ```javascript function uploadFile() { var fileInput = document.getElementById('fileInput'); var selectedFile = fileInput.files[0]; var filePath = URL.createObjectURL(selectedFile); // 或者,如果你想要完整的系统路径,可以使用FileReader API // var reader = new FileReader(); // reader.onload = function(e) { // filePath = e.target.result; // }; // reader.readAsDataURL(selectedFile); $.ajax({ url: '@Url.Action("Upload", "YourController")', // 替换为你的控制器和动作名 type: 'POST', data: { file: filePath }, processData: false, // 因为我们不需要处理数据,它已经是原始二进制数据 contentType: false, success: function(response) { $('#filePath').text(response.message); // 显示服务器返回的信息 } }); } ``` 后端Controller接收文件的代码(C#示例): ```csharp [HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string fullPath = Path.Combine(Server.MapPath("~/uploads/"), file.FileName); file.SaveAs(fullPath); // 将文件保存到指定路径 return Json(new { message = "文件已上传" }, JsonRequestBehavior.AllowGet); // 返回JSON消息 } else { return Json(new { message = "请选择有效文件" }, JsonRequestBehavior.AllowGet); } } ``` 注意:以上代码需要在服务器环境运行,因为`Server.MapPath`函数依赖于服务器的实际目录结构。同时,记得处理可能出现的安全问题,比如检查文件类型、大小等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值