search
HomeWeb Front-endJS TutorialAdvanced JavaScript (9) JS implements uploading local files to Alibaba Cloud server

JS implements local file uploading to Alibaba Cloud server

Preface

In the previous blog "JavaScript Advanced (8) JS implements image preview and import server function" (click to view details) In , JS is implemented to preview and upload local image files to the Alibaba Cloud server. This time you need to upload the locally packaged files to the Alibaba Cloud server. This operation cannot be accomplished using the previous image file upload method. The operation interface is as follows:

Ideas

The format of files transferred between local and server should be the familiar Base64 format. First, you need to convert the local file into Base64 format. After transferring it to the server, the file in Base64 format is converted into the original file on the server side.

Source code analysis

Controller

/*--------------移动APP版本管理G030 G031-------------------------*/
medModule.controller('VersionController',function($scope, $http){
$scope.queryFun = function() {
try{
appCallServer($http,"G030",{"mangid":localStorage.mangid
},
//success function
function(data){
$scope.currentVersion = data.version;
},
//fail function
function(data){
//alert("未找到记录:"+data.errtext);
});
}catch(error){
alert("G030:"+error.message);
}
};
$scope.queryFun();
// 上传文件
$scope.doTx = function() {
var appBase64 = document.getElementById("appBase64").innerHTML;	// 获取文件Base64编码内容
var sunny = document.getElementById("appName").innerHTML;	// 获取文件名称(PS:瞬间感觉自己好聪明啊~~)
var appName = sunny.substr(0, sunny.length-4); // 获取子字符串。
/*alert(appBase64);
alert(appName);*/
if(appBase64.length == 0){
alert("请选择有效文件[该文件为空]");
}
try {
appCallServer($http, "G031", {
"mangid"   : localStorage.mangid,
"appBase64": appBase64,
"appVersion"  : appName
},
// success function
function(data) {
alert("上传文件成功");
},
// fail function
function(data) {
alert("上传文件失败:" + data.errtext);
});
} catch (error) {
alert("G031:" + error.message);
}
};
});

Html script

<script type="text/javascript">  
function loadAppFile(source) {
var file = source.files[0];
if (window.FileReader) {
var fr = new FileReader();
// onloadend读取完成触发,无论成功或失败.如果读取失败,则 result的值为 null,否则即是读取的结果
fr.onloadend = function(e) {
var content = e.target.result;
if(content != null){
var arr = content.toString().split(",");
// 将文件Base64编码内容传至页面
document.getElementById("appBase64").innerHTML = arr[1];
// 获取图片名称(PS:瞬间感觉自己好聪明啊~~) 
document.getElementById("appName").innerHTML = document.getElementById("appInput").files[0].name;
/* alert(document.getElementById("appInput").files[0].name);
alert(document.getElementById("appName").innerHTML);
alert(document.getElementById("appBase64").innerHTML); */
}
};
fr.readAsDataURL(file);
}
}
</script>

Server receiving code

/************************* 更新移动APP版本信息 *************************/
public static boolean do_G031(RequestMessage request,ResponseMessage response){
logger.info("\n\n------------Update_APP_G031 debug info-------------\n请求数据包信息:" + request.json.toString());
if(!Pubf.checkMangSession(request,response)){
return(false);
}
try{
String app,version;
app	= request.getString("appBase64").trim();
version	= request.getString("appVersion").trim();
/*--------------------------- 将应用存进服务端 ---------------------------*/
if(!app.equals("")){
logger.info("开始写文件.....");
FileUtil.GenerateApp(app, MyConst.APP_FILE_PATH + version + ".wgt");
logger.info("写文件完成.....");
/*-------------------------将应用版本号写进版本文件--------------------------*/
logger.info("开始写入版本号.....");
FileUtil.writeFile(MyConst.APP_VERSION_FILE_PATH, version);
logger.info("写版本号完成.....");
return(true);
}else{
return(false);
}
}catch(Exception e){
e.printStackTrace();
response.errtext = "移动APP更新失败";
response.result  = MyConst.ERR_FORMAT;
return(false);
}
}

Tool class

<pre name="code" class="java">/**
 * 
 * @param appStr 应用内容
 * @param appFilePath 应用存放路径
 * @return
 */
public static boolean GenerateApp(String appStr, String appFilePath) { // 对字节数组字符串进行Base64解码并生成wgt更新包
if (appStr == null) // 文件数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(appStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成wgt应用
OutputStream out = new FileOutputStream(appFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

The content of the read file is as follows:

As can be seen from the above figure, the encoding method is exactly the Base64 encoding method we mentioned before. Then the next work will be easy. Just follow the idea of ​​​​previous image processing.

During this period, I also encountered some problems. For example

Hide the position of the element. Try to place it as close to the submit button as possible, otherwise its content cannot be obtained in the controller.

After the above steps, you can upload the update package to the corresponding update folder on the server, and write the update package version number information into the corresponding version.txt file.

Code Comprehension

Comparing the above code with the image uploading done before, we found that the two methods of data acquisition are different. This article uses the FileReader method of HTML5 (click to view details). Applying this method when uploading images before can also solve the problem. The two methods of writing to the server are the same, both writing Base64 encoded content into the file. When your thinking is clear, problems will naturally be easily solved.

Further Optimization

Happiness is never satisfied. During the above file upload process, larger files will be uploaded. For this, you may need to wait for 1 minute or even several minutes. This is unacceptable. Something to endure. In order to enhance the user experience. A progress bar beautification effect is specially added for file upload. See the next blog for details.

美文美图


The above is JavaScript advanced (9) JS implementation of uploading local files to Alibaba Cloud server For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Related articles:

The mobile terminal implements the file upload function through HTML5

File upload image in php

Detailed introduction to file upload of HTML5 application

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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment