Home  >  Article  >  Web Front-end  >  How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

寻∝梦
寻∝梦Original
2018-09-07 14:22:211627browse

This article mainly talks about the file upload function of angularjs. Anyone who doesn’t understand it can read it. I hope it can help everyone. Let us read this article together

Problem descriptionAttachment upload

The test results are uploaded as attachments.

How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

Ignore api here.

The task achieved is to click to select the file, and then the file can be cleared after selection.

Plug-in introduction

A plug-in that has been reflected in the project is used, angular-file-upload.

The plug-in is very simple, it is an instruction. We declare an uploader object in the instruction it provides us. This object represents what operations are to be performed at different times. Another Observer pattern.

Function implementation

Using instructions

The official website gives many ways to use this instruction. Here we choose the simplest one, Single, single file upload. .

How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

<input>

A input of type file, using nv-file-selectInstruction, pass an uploader object to the instruction as a parameter.

Very simple logic, create a new FileUploader object, and then rewrite its onAfterAddingFile method, that is, after the file is added, click to select the file. Select the file and click a method to execute after completion.

In this method we directly upload the file.

// 新建文件上传实例
self.uploader = new FileUploader();

// 重写文件添加后的方法
self.uploader.onAfterAddingFile = function(fileItem) {
    // 打印日志
    if (config.debug) { console.info('onAfterAddingFile', fileItem); }
    // 上传文件
    self.upload(fileItem);
};

// 传给视图
$scope.uploader = self.uploader;

If the file upload is encapsulated into a command, the above code should be executed in the controller method of the method command! ! !

For detailed explanation of the execution of compile, controller, link in the directive, please refer to Correctly Using compile in Angular Directive , controller and link.

Cause analysis

It may be that the nv-file-select directive is used to bind various events in the link function during implementation. Timing requires our uploader object.

And if we put it in the link function, the link function of this instruction is later than nv-file-select linkThe function is executed, so it is invalid.

upload

// 上传文件
self.upload = function(data) {
    // 上传文件
    AttachmentService.uploadFile(data._file)
        .then(function success(response) {
                // 将上传成功的附件绑定再ngModel中
                $scope.ngModel = response.data;
                // 显示上传按钮
                self.showClear();
            }, function error() {
                // 提示用户上传失败
                sweetAlert.swal({
                    title: "对不起",
                    text: "上传的附件不能大于1M,请确认附件是否大于1M"
                });
            });
};

Clear

What should I do if the user uploads the wrong file? Add a clear button that will be displayed after uploading a file.

// 清空选中文件
self.clear = function() {
    self.deleteFile(scope.ngModel.id);
};

// 删除附件
self.deleteFile = function(id) {
    AttachmentService.deleteFile(id, function success() {
        // 将附件赋为空对象
        scope.ngModel = undefined;
        // 隐藏清空按钮
        self.hideClear();
    });
};

scope.clear = self.clear;

But there is a problem here. The attachment on the server is only deleted, but the file selection effect is still there, and the selected file name is still displayed here.

How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

The solution is to wrap it with a form and set the type of button to reset, when the button is clicked, the contents in input will be cleared. New problems will arise after


    
                 

            <input>         

        

                     

    

    <input>     

is set to reset, because this command is set in a form form, so reset , and cleared out all the others.

ng-form

Getng-form solved the problem.

This is the official explanation of the ng-form directive:

HTML does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.

HTML does not allow nesting of form elements, ng-form is used to nest form if a child form group needs to be validated. (If you want to see more, go to the PHP Chinese website angularjs learning manual to learn)

But ng-form does not implement the function of form , ng-submit cannot be used. It is reasonable to think about this design. If ng-form can also be submit, nested form, a button of submit, who is submitting?

Optimization

This is just the simplest application scenario. What if you need to upload a large file with dozens of M?

How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

If you are a friend who has studied computer networks, do you feel familiar when you see this implementation? Isn't this what the router does when it finds that another network cannot carry so much data at once? The principle of computer network is still somewhat useful.

Just like when I designed the yunzhiTrueOrFalse filter last time, I understood the essence of the data structure. Data structures are actually data "structures".

We say that Map is a data structure, but can we complete the task without HashMap?

can also be used, two arrays, one to store key, one to store value, for loop. Then the Java community found that there were too many application scenarios for this and it was too troublesome to use, so they implemented such a data structure HashMap in JDK. (This is a story I made up!)

After abstraction, everything is more convenient. If one day you find that the existing data structure cannot meet your scene needs, open the book and design one yourself.

This article ends here. If you want to see more, it is recommended to learn from the PHP Chinese website angularjs Reference Manual.


The above is the detailed content of How much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn