search
HomeWeb Front-endJS TutorialHow much do you know about the AngularJS file upload function? Let you know about angularjs file upload in a few minutes

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
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.