Table of Contents
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" >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
Plug-in introduction
Function implementation
Using instructions
Cause analysis
upload
Clear
ng-form
Optimization
Home Web Front-end JS Tutorial 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

Sep 07, 2018 pm 02:22 PM
angularjs File Upload

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>
Copy after login

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;
Copy after login

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"
                });
            });
};
Copy after login

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;
Copy after login

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

Copy after login
Copy after login
    
                 

            <input>         

        

                     

    
Copy after login
Copy after login
    <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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

How to solve Java file upload exception (FileUploadException) How to solve Java file upload exception (FileUploadException) Aug 18, 2023 pm 12:11 PM

How to solve Java file upload exception (FileUploadException). One problem that is often encountered in web development is FileUploadException (file upload exception). It may occur due to various reasons such as file size exceeding limit, file format mismatch, or incorrect server configuration. This article describes some ways to solve these problems and provides corresponding code examples. Limit the size of uploaded files In most scenarios, limit the file size

How to implement FTP file upload progress bar using PHP How to implement FTP file upload progress bar using PHP Jul 30, 2023 pm 06:51 PM

How to use PHP to implement FTP file upload progress bar 1. Background introduction In website development, file upload is a common function. For the upload of large files, in order to improve the user experience, we often need to display an upload progress bar to the user to let the user know the file upload process. This article will introduce how to use PHP to implement the FTP file upload progress bar function. 2. The basic idea of ​​implementing the progress bar of FTP file upload. The progress bar of FTP file upload is usually calculated by calculating the size of the uploaded file and the size of the uploaded file.

File Uploading and Processing in Laravel: Managing User Uploaded Files File Uploading and Processing in Laravel: Managing User Uploaded Files Aug 13, 2023 pm 06:45 PM

File Uploading and Processing in Laravel: Managing User Uploaded Files Introduction: File uploading is a very common functional requirement in modern web applications. In the Laravel framework, file uploading and processing becomes very simple and efficient. This article will introduce how to manage user-uploaded files in Laravel, including verification, storage, processing, and display of file uploads. 1. File upload File upload refers to uploading files from the client to the server. In Laravel, file uploads are very easy to handle. first,

PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files Jul 30, 2023 pm 02:03 PM

PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files In developing web applications, file upload is a common requirement. PHP provides a convenient function move_uploaded_file() for processing uploaded files. This article will introduce you how to use this function to implement the file upload function. 1. Preparation Before starting, make sure that your PHP environment has been configured with file upload parameters. You can do this by opening php.in

Simplify file upload processing with Golang functions Simplify file upload processing with Golang functions May 02, 2024 pm 06:45 PM

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

See all articles