gpt4 book ai didi

javascript - AngularJS 使用 ng-upload 上传图片

转载 作者:IT王子 更新时间:2023-10-29 03:16:33 25 4
gpt4 key购买 nike

我正在尝试使用 ng-upload 在 AngularJS 中上传文件,但我遇到了问题。我的 html 看起来像这样:

<div class="create-article" ng-controller="PostCreateCtrl">
<form ng-upload method="post" enctype="multipart/form-data" action="/write" >
<fieldset>
<label>Category</label>
<select name="category_id" class="">
<option value="0">Select A Category</option>
<?php foreach($categories as $category): ?>
<option value="<?= $category -> category_id; ?>"><?= $category -> category_name; ?></option>
<?php endforeach; ?>
</select>

<label>Title</label>
<input type="text" class="title span5" name="post_title"
placeholder="A catchy title here..."
value="<?= $post -> post_title; ?>" />

<label>Attach Image</label>
<input type="file" name="post_image" />

<a href='javascript:void(0)' class="upload-submit: uploadPostImage(contents, completed)" >Crop Image</a>

<label>Body</label>
<div id="container">
<textarea id="mytextarea" wrap="off" name="post_content" class="span7" placeholder="Content..."><?= $post -> post_content; ?></textarea>
</div>
<div style='clear:both;'></div>
<label>Preview</label>
<div id='textarea-preview'></div>

</fieldset>
<div class="span7" style="margin: 0;">
<input type="submit" class="btn btn-success" value="Create Post" />
<input type="submit" class="btn btn-warning pull-right draft" value="Save as Draft" />
</div>

</form>
</div>

我的 js Controller 看起来像这样:

ClabborApp.controller("PostCreateCtrl", ['$scope', 'PostModel',
function($scope, PostModel) {

$scope.uploadPostImage = function(contents, completed) {
console.log(completed);
alert(contents);
}

}]);

我面临的问题是,当裁剪图像被点击并执行 uploadPostImage 时,它​​会上传整个表单。不是期望的行为,但我可以让它工作。最大的问题是在 js 中,函数 uploadPostImage 'contents' 参数总是未定义,即使 'completed' 参数返回为 true。

目标是只上传一张图片进行裁剪。我在这个过程中做错了什么?

最佳答案

几乎没有关于上传文件 Angular 文档。许多解决方案需要自定义指令其他依赖项(primis 中的 jquery...只是为了上传文件...)。经过多次尝试,我只用 angularjs 发现了这个(在 v.1.0.6 上测试过)

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) 不支持“输入文件”标签上的 ng-model,因此您必须以传递所有(最终)选定文件的“ native 方式”进行操作来自用户。

控制者

$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);

$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );

};

最酷的部分是 undefined content-type 和 transformRequest: angular.identity 在 $http 上可以选择正确的“content-type”并管理处理多部分数据时所需的边界。

关于javascript - AngularJS 使用 ng-upload 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17216806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com