django ajax上传文件

来源:互联网 发布:vm安装mac os 编辑:程序博客网 时间:2024/05/22 12:44
文件上传

https://www.bbsmax.com/A/l1dyQexdem/


  <script type="text/javascript">
            function uploadImage() {
                $.ajaxFileUpload({
                    url: "/Struts2Upload/test/uploadAjax.action",
                    secureuri:false,
                    fileElementId:"btn_file",
                    data:{lbg:"json传值并且返回"},
                    dataType: "json",
                    error: function(data, status, e) {
                        alert("shibai");
                        alert(e);
                    },
                    success: function(data, textStatus) {
                        alert(textStatus);
                        $('img').attr('src',data.imPath);
                       
                    }
                });
            }
 
        </script>

<input type="file" id="btn_file" name="btn_file" onchange="uploadImage();">

处理图片:

def pic_class(request):    upload_file = request.FILES.get("myfile", None)  # 获取上传的文件,如果没有文件,则默认为None    file_obj = request.FILES.get('file')    if file_obj:   # 处理附件上传到方法        request_set = {}        print('file--obj', file_obj)        # user_home_dir = "upload/%s" % (request.user.userprofile.id)        # accessory_dir = settings.accessory_dir        # if not os.path.isdir(accessory_dir):        #     os.mkdir(accessory_dir)        scr = Image.open(file_obj)        img= np.asarray(scr)
with open(upload_file, 'wb') as new_file:    for chunk in file_obj.chunks():        new_file.write(chunk)


### get the inmemory file
data = request.FILES.get('btn_file') # get the file from the curl
### write the data to a temp file
tup = tempfile.mkstemp() # make a tmp file
f = os.fdopen(tup[0], 'w') # open the tmp file for writing
f.write(data.read()) # write the tmp file
f.close()
### return the path of the file
filepath = tup[1] # get the filepath
return filepath

原创粉丝点击