android 复习和NOde JS 学习篇 模拟登陆,文件上传Demo
NOde JS 服务代码:模拟登陆
var express = require(‘express’);
var app = express();
app.use(express.static(‘public’));
app.get(‘/index.htm’, function (req, res) {
res.sendFile( __dirname + “/” + “index.htm” );
})
app.get(‘/process_get’, function (req, res) {
res.charset = ‘utf-8’;
// 输出 JSON 格式
var response = {
“username”:req.query.username,
“pwd”:req.query.pwd
};
var sucess={
“sucess”:”成功”,
}
var fail={
“fail”:”失败,用户名或者密码错误!”,
}
console.log(response);
var username=req.query.username;
var pwd=req.query.pwd;
if (username===’gsc’&&pwd===’123456’){
res.end(JSON.stringify(sucess));
}
else{
res.end(JSON.stringify(fail));
}
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
2 文件上传
var express = require(‘express’);
var app = express();
var fs = require(“fs”);
var bodyParser = require(‘body-parser’); // 中间件引入
//app.use(bodyParser.urlencoded());
var multer = require(‘multer’); //中间件引入
app.use(express.static(‘public’));// 当前Public 目录下 资源引用
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: ‘/tmp/’}).array(‘image’));// 上传文件的目录和Key 值
app.get(‘/index.htm’, function (req, res) {
res.sendFile( __dirname + “/” + “index.htm” );// 访问路由处理
})
// 处理上传的匿名方法
app.post(‘/file_upload’, function (req, res) {
console.log(req.files[0]); // 上传的文件信息
var des_file = __dirname + “/” + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:’File uploaded successfully’,
filename:req.files[0].originalname
};
}
console.log( response );
res.end( JSON.stringify( response ) );//返回规定格式JSON 字符串
});
});
})
// 设置服务器端口号:
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log(“应用实例,访问地址为 http://%s:%s“, host, port)
})
客户端( Android 端代码)
package com.org.gsc.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
/**
* Created by qundui on 2017/7/17.
*/
public class NetDemo extends Activity implements View.OnClickListener {
private static final int PHOTO_PICKED_WITH_DATA = 200;
private EditText username,pwd;
private Button upload;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.netdemo);
username= (EditText) findViewById(R.id.et_username);
pwd= (EditText) findViewById(R.id.et_pwd);
upload= (Button) findViewById(R.id.upload);
upload.setOnClickListener(this);
}
public void login(View view){
String userName=username.getText().toString().trim();
String pwdstr=pwd.getText().toString().trim();
RequestParams entity=new RequestParams(“http://192.168.1.101:8081/process_get“);
entity.addBodyParameter(“username”,userName);
entity.addBodyParameter(“pwd”,pwdstr);
x.http().get(entity, new Callback.CommonCallback() {
@Override
public void onSuccess(String result) {
System.out.println(“—onSuccess–”+result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
}
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==PHOTO_PICKED_WITH_DATA){
ContentResolver resolver = getContentResolver();
//照片的原始资源地址
Uri originalUri = data.getData();
// 获取照片路径
String[] proj = {MediaStore.Images.Media.DATA};
// 好像是Android多媒体数据库的封装接口,具体的看Android文档
Cursor cursor = managedQuery(originalUri, proj, null, null, null);
// 按我个人理解 这个是获得用户选择的图片的索引值
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// 将光标移至开头 ,这个很重要,不小心很容易引起越界
cursor.moveToFirst();
// 最后根据索引值获取图片路径
String path = cursor.getString(column_index);
try {
//使用ContentProvider通过URI获取原始图片
Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
if (photo != null) {
uploadFile(photo);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
File file;
public File saveBitmapFile(Bitmap bitmap) {
file = new File("/mnt/sdcard/01.jpg");//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void uploadFile(Bitmap cameraBitmap) {
String url="http://192.168.1.101:8081/file_upload";
List<File> sum=new ArrayList<>();
sum.add(saveBitmapFile(cameraBitmap));
uploadFiles(url,"image",sum);
}
private void uploadFiles(String url, String keyName, List<File> files){
OkGo.post(url)//
.tag(this)//
.isMultipart(true) // 强制使用 multipart/form-data 表单上传(只是演示,不需要的话不要设置。默认就是false)
//.params("param1", "paramValue1") // 这里可以上传参数
//.params("image", new File("filepath1")) // 可以添加文件上传
//.params("file2", new File("filepath2")) // 支持多文件同时添加上传
.addFileParams(keyName, files) // 这里支持一个key传多个文件
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, okhttp3.Response response) {
System.out.println("------"+s);
}
});
}
}
客户端网页代码“
登陆:
密码:
2,文件上传
文件上传表单
文件上传:
选择一个文件上传: