xutils上传文件到服务器

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;


public class AndroidUtil {


// 返回一个列表对话框
public static AlertDialog.Builder getListDialogBuilder(Context context,
String[] items, String title, OnClickListener clickListener) {
return new AlertDialog.Builder(context).setTitle(title).setItems(items, clickListener);

}
}



import java.io.ByteArrayOutputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


public class MainActivity extends Activity {


private ImageView img;
private Button btnUpload;
private HttpUtils httpUtils;
private String URL="http://192.168.12.93:8080/Person_proj/upload";


private String[] items = { "拍照", "相册" };
private String title = "选择照片";


private static final int PHOTO_CARMERA = 1;
private static final int PHOTO_PICK = 2;
private static final int PHOTO_CUT = 3;
// 创建一个以当前系统时间为名称的文件,防止重复
private File tempFile = new File(Environment.getExternalStorageDirectory(),
getPhotoFileName());


// 使用系统当前日期加以调整作为照片的名称
private String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("'PNG'_yyyyMMdd_HHmmss");
return sdf.format(date) + ".png";
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


img = (ImageView) findViewById(R.id.main_img);
btnUpload = (Button) findViewById(R.id.upload);
btnUpload.setOnClickListener(clickListener);
img.setOnClickListener(clickListener);

httpUtils=new HttpUtils(10000);
}


private OnClickListener clickListener = new OnClickListener() {


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_img:
AlertDialog.Builder dialog = AndroidUtil.getListDialogBuilder(
MainActivity.this, items, title, dialogListener);
dialog.show();
break;
case R.id.upload:
upload();
break;


default:
break;
}


}
};

// 上传文件到服务器
protected void upload() {
RequestParams params=new RequestParams();
params.addBodyParameter(tempFile.getPath().replace("/", ""), tempFile);
httpUtils.send(HttpMethod.POST,URL, params,new RequestCallBack<String>() {


@Override
public void onFailure(HttpException e, String msg) {
Toast.makeText(MainActivity.this, "上传失败,检查一下服务器地址是否正确", Toast.LENGTH_SHORT).show();
Log.i("MainActivity", e.getExceptionCode() + "====="
+ msg);
}


@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Toast.makeText(MainActivity.this, "上传成功,马上去服务器看看吧!", Toast.LENGTH_SHORT).show();
Log.i("MainActivity", "====upload_error====="
+ responseInfo.result);
}
});
}


private android.content.DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// 调用拍照
startCamera(dialog);
break;
case 1:
// 调用相册
startPick(dialog);
break;


default:
break;
}
}
};


// 调用系统相机
protected void startCamera(DialogInterface dialog) {
dialog.dismiss();
// 调用系统的拍照功能
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("camerasensortype", 2); // 调用前置摄像头
intent.putExtra("autofocus", true); // 自动对焦
intent.putExtra("fullScreen", false); // 全屏
intent.putExtra("showActionIcons", false);
// 指定调用相机拍照后照片的存储路径
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
startActivityForResult(intent, PHOTO_CARMERA);
}


// 调用系统相册
protected void startPick(DialogInterface dialog) {
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
startActivityForResult(intent, PHOTO_PICK);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_CARMERA:
startPhotoZoom(Uri.fromFile(tempFile), 300);
break;
case PHOTO_PICK:
if (null != data) {
startPhotoZoom(data.getData(), 300);
}
break;
case PHOTO_CUT:
if (null != data) {
setPicToView(data);
}
break;


default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}


// 调用系统裁剪
private void startPhotoZoom(Uri uri, int size) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// crop为true是设置在开启的intent中设置显示的view可以裁剪
intent.putExtra("crop", true);
// aspectX,aspectY是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX,outputY是裁剪图片的宽高
intent.putExtra("outputX", size);
intent.putExtra("outputY", size);
// 设置是否返回数据
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTO_CUT);
}


// 将裁剪后的图片显示在ImageView上
private void setPicToView(Intent data) {
Bundle bundle = data.getExtras();
if (null != bundle) {
final Bitmap bmp = bundle.getParcelable("data");
img.setImageBitmap(bmp);


saveCropPic(bmp);
Log.i("MainActivity", "path==="+tempFile.getAbsolutePath());
}
}


// 把裁剪后的图片保存到sdcard上
private void saveCropPic(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fis = null;
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
try {
fis = new FileOutputStream(tempFile);
fis.write(baos.toByteArray());
fis.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != baos) {
baos.close();
}
if (null != fis) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}


}
以下是两种Python文件服务器的实现方式: 1. 使用Python 2.x自带的SimpleHTTPServer模块实现简单文件下载和上传服务: - 在命令行中进入需要共享文件的目录,执行以下命令即可启动文件下载服务: ```shell python -m SimpleServer 8081 ``` 这将在本地8081端口启动一个简单的文件下载服务,可以通过浏览器访问http://localhost:8081来下载共享的文件。 - 如果需要启动带上传功能的文件服务,可以使用SimpleHTTPServerWithUpload.py脚本,该脚本需要先下载并保存到需要共享文件的目录下,然后执行以下命令即可启动文件上传和下载服务: ```shell python SimpleHTTPServerWithUpload.py 8089 ``` 这将在本地8089端口启动一个带上传和下载功能的文件服务,可以通过浏览器访问http://localhost:8089来上传和下载共享的文件。 2. 使用Python Flask框架实现带认证功能的文件服务器: - 首先需要安装Flask框架,可以使用以下命令进行安装: ```shell pip install flask ``` - 然后可以使用以下代码实现带认证功能的文件服务器: ```python from flask import Flask, request, send_from_directory from werkzeug.utils import secure_filename import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' app.config['DOWNLOAD_FOLDER'] = 'downloads' app.config['ALLOWED_EXTENSIONS'] = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app.config['USERNAME'] = 'admin' app.config['PASSWORD'] = 'password' def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] @app.route('/uploads', methods=['POST']) def upload_file(): if request.method == 'POST': username = request.authorization.username password = request.authorization.password if username != app.config['USERNAME'] or password != app.config['PASSWORD']: return 'Unauthorized', 401 file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return 'File uploaded successfully' else: return 'Invalid file type', 400 @app.route('/downloads/<filename>', methods=['GET']) def download_file(filename): username = request.authorization.username password = request.authorization.password if username != app.config['USERNAME'] or password != app.config['PASSWORD']: return 'Unauthorized', 401 return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename) if __name__ == '__main__': app.run(debug=True) ``` 这将在本地启动一个带认证功能的文件服务器,可以通过浏览器访问http://localhost:5000/uploads来上传文件,访问http://localhost:5000/downloads/<filename>来下载文件,其中<filename>是需要下载的文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值