我有一个视图和序列化器:
class UserView(generics.RetrieveUpdateAPIView):
model = get_user_model()
serializer_class = UserProfileSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_object(self, *args, **kwargs):
return self.request.user
class UserImageSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('image',)
Run Code Online (Sandbox Code Playgroud)
他们与httpie合作很好:
http -f put localhost:8000/accounts/api/image/ "Authorization: Token mytoken" image@~/Downloads/test.jpg
HTTP/1.0 200 OK
Allow: GET, PUT, PATCH, HEAD, OPTIONS
Content-Type: application/json
Date: Thu, 03 Sep 2015 22:50:33 GMT
Server: WSGIServer/0.2 CPython/3.4.3
Vary: Accept
X-Frame-Options: SAMEORIGIN
{
"image": "http://localhost:8000/media/accounts/user_images/test.jpg"
}
Run Code Online (Sandbox Code Playgroud)
并且我的图片已上传并显示在管理员中.
现在我希望能够使用AJAX上传文件,但显然不想工作:
<form action="http://localhost:8000/accounts/api/image/"
method="put"
enctype="multipart/form-data">
<input name="image" type="file">
<input type="submit">
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> …Run Code Online (Sandbox Code Playgroud) 假设我有一个包含一些图像的数组:
var images = [image1, image2, image3]
Run Code Online (Sandbox Code Playgroud)
如何在单个请求中使用 AJAX 将这些图像发送到 php 文件?
以下代码不起作用:
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: {data: images},
success: function(data) {
alert(data);
location.reload();
}
});
Run Code Online (Sandbox Code Playgroud)
我的 HTML:
<div id="newPostFile">
<label for="newPostFiles"><i class="fa fa-file-text-o" id="newPostFileIcon" aria-hidden="true"></i></label>
<input type="file" name="newPostFiles" id="newPostFiles">
</div>
Run Code Online (Sandbox Code Playgroud)
Endgoal: Whenever a file is selected, the file is added to the array and when the submit button is clicked, all the files are uploaded at once.
我想知道为什么我不能使用$ .post()方法在JQuery中上传文件?
有没有办法调整请求能够处理这个?
$.post(url, { file: fileName, path: "/uploads" }, function (result) {});
Run Code Online (Sandbox Code Playgroud)