【问题标题】:Django restful api can not get file contentDjango restful api 无法获取文件内容
【发布时间】:2018-02-05 12:23:57
【问题描述】:

我使用 Django restful api + angularjs 。 现在,我通过 Django restful api 附加使用 angularjs 将文件上传到服务器 在web前端,Html是:

<input type="file" data-upload-file id="uploadInputFile">

angularjs的代码是:

omapp.directive("uploadFile",function(httpPostFactory){
    return {
        restrict:"A",
        scope:true,
        link:function(scope,element,attr){
            element.bind('change',function(){
                var formData = new FormData();
                formData.append('file', element[0].files[0]);             
                console.log(formData.get('file'))         

    httpPostFactory('/api/uploadfile/',formData.get('file'),function (callback) {
                        console.log(callback);
                    })
                })
            }
        };

    });

omapp.factory('httpPostFactory', function ($http,$cookies) {
    return function (file, data, callback) {
                    var req = {
                         method:"POST",
                         url:file,
                         headers:{
                             'X-CSRFToken':$cookies.get('csrftoken')
                         },
                         data:{file:data}
                   }
                   $http(req)
                   .then(function successcallback(response){callback(response);})

    }
});

一切正常。但是 Django api 无法获取数据 代码是:

 class UploadFile(APIView):
     def post(self,request,format=None):
         logger.info("file content");
         logger.info(request.data)
         return Response("upload done")

如何获取数据?

【问题讨论】:

    标签: python angularjs django rest


    【解决方案1】:

    在 django rest 调用中处理文件上传的更好方法是使用 base64 格式。在前端将您的文件编码为 base64 字符串,并在 django 中再次将其解码为原始文件。示例代码here。

    【讨论】:

      【解决方案2】:

      你需要从request.FILES

      中获取
      def post(self,request,format=None):
           file_data = request.FILES['file']
           return Response("upload done")
      

      【讨论】:

      • 当我使用“request.FILES['file']”时,遇到一个错误:angular.js:14727 可能是未处理的拒绝...
      • 未处理的拒绝,可能是500键错误。检查你的浏览器控制台,你的请求数据有文件内容,
      • 我收到一个新错误:MultiValueDictKeyError at /api/uploadfile/ "'file'"
      • 可以在 /api/uploadfile/ "'file'" 发布你的最新代码 chanes 得到这个错误 MultiValueDictKeyError
      【解决方案3】:

      我得到了答案: Html 是:

      <input type="file" data-upload-file id="uploadInputFile">
      

      angularjs是:

      omapp.directive("uploadFile",function(httpPostFactory){
          return {
              restrict:"A",
              scope:true,
              link:function(scope,element,attr){
                  element.bind('change',function(){
                      var formData = new FormData();
                      formData.append('file', element[0].files[0]);             
                      console.log(formData.get('file'))         
      
          httpPostFactory('/api/uploadfile/',formData.get('file'),function (callback) {
                              console.log(callback);
                          })
                      })
                  }
              };
      
          });
      
      omapp.factory('httpPostFactory', function ($http,$cookies) {
          return function (file, data, callback) {
                          var req = {
                               method:"POST",
                               url:file,
                               headers:{
                                   'X-CSRFToken':$cookies.get('csrftoken'),
                                    Content-Type': undefined //add this
                               },
                               data:{file:data}
                         }
                         $http(req)
                         .then(function successcallback(response){callback(response);})
      
          }
      });
      

      宁静的API:

      class UploadFile(APIView):
           def post(self,request,format=None):
               logger.info("read file ");
               up_file = request.FILES['file']
               logger.info(up_file)   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多