美文网首页
js、ajax上传向服务器上传文件

js、ajax上传向服务器上传文件

作者: Aedda | 来源:发表于2021-04-20 11:46 被阅读0次
<button onclick="f()">测试</button>
<script>
    function f() {
        var url = "http://img12.360buyimg.com/pop/s590x470_jfs/t1/176374/26/2467/95533/606d5056Ee3dde2e6/d6c7d0638cc5e2db.jpg"
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.responseType = 'blob'
        xhr.onload = () => {
            const blob = xhr.response
            console.log(blob)
            //生成文件
            const File = new window.File([blob], `abc.${blob.type.split('/')[1]}`, {type: blob.type})
            //将文件放在formData中post给后端
            var formData = new FormData()
            formData.append('media', File)
            $.ajax({
                url: "/api/import_file/",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    console.log(1111, res)
                }
            })
        }
        xhr.send()
    }
</script>
    def post(self, request):
        data = {i: request.POST.get(i) for i in request.POST}
        for k, v in data.items():
            if not v:del data[k]
            elif 'date' in k:data[k] = parse(v).date()
        endswith = os.path.splitext(request.FILES.get('media').name)[-1]
        data['file_name'] = f'{uuid.uuid1()}{endswith}'
        with open(os.path.join('crawler', 'download', data['file_name']), 'wb') as wb:
            for i in request.FILES.get('media').chunks():
                wb.write(i)
            wb.close()

相关文章

网友评论

      本文标题:js、ajax上传向服务器上传文件

      本文链接:https://www.haomeiwen.com/subject/lutnlltx.html