上传图片到django

2017-07-20  本文已影响20人  哈喽jv

Android正确姿势:

要上传的图片文件:

file =newFile(imagepxh.getPath());

RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"),file);

//map.put("post_imag", requestBody);

//todo千万要加上filename="" (这是重点)

map.put("post_imag"+ i +"\"; filename=\""+ file.getName(),requestBody);

retrofit的接口:

@Multipart//表单提交

@POST(".")

ObservablepostSnippetWithImag(@Part("res") RequestBody s,@PartMapMap map);


Django的正确姿势:


Django的Model:

class Post(models.Model):

      post_imag= models.FileField(upload_to='imgs/',blank=True)

Django服务端的View:

@api_view(['POST'])

@permission_classes((AllowAny,))#接口的访问权限设置http://www.django-rest-framework.org/api-guide/permissions/

def save_post(request):

       if request.method =='POST':

      data = request.data

      files = data['post_imag1']

      post = Post(village=village,created_time=timezone.now())

      post.post_imag = files

       post.save()

       returnResponse("上传成功",status=status.HTTP_201_CREATED)

returnResponse("上传失败",status=status.HTTP_400_BAD_REQUEST)

上一篇下一篇

猜你喜欢

热点阅读