项目上传图片到后台,前端总是传不上去,翻阅代码,详细查看,原来是php的头和java的不同。

总体的思路是,可以拍照上传,也可以本地上传。利用onActivityResult,从返回的Intent中得到Bitmap对象。

如果是文件系统中的图片又分为content://开头和file://开头,给予判断即可。

又:java和php服务器后台传输数据时,解析不同的头,下面上代码:

public class CameraTest extends Activity {
Bitmap photo = null;
String filename="";
String picPath="";
ImageView imageview;
Button mPic,mUpload;
static String path="http://xxx.xxx.x.xx/xxxr.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
imageview=(ImageView) findViewById(R.id.imageview);
mPic=(Button) findViewById(R.id.pic);
mUpload=(Button) findViewById(R.id.upload);
mUpload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(photo!=null){
String srcPath = Environment.getExternalStorageDirectory()+ "/imgs/"+filename;
new CommentAsyncTask().execute(srcPath);
}
}
});
mPic.setOnClickListener(new Onclicklistenerimpl2());
}
class CommentAsyncTask extends AsyncTask<String, Integer, String> {

@Override
protected String doInBackground(String... params) {
uploadFile(params[0]);
return "";
}

@Override
protected void onPostExecute(String result) {
//
super.onPostExecute(result);
}
}
// ///上传图片/
private class Onclicklistenerimpl2 implements OnClickListener {
private String[] method = { "拍照上传", "本地上传" };

@Override
public void onClick(View v) {
dialog();

}

private void dialog() {
AlertDialog ad = new AlertDialog.Builder(CameraTest.this)
// .setIcon(R.drawable.ic_launcher)
.setItems(method, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
String state = Environment
.getExternalStorageState();

if (state.equals(Environment.MEDIA_MOUNTED)) {

Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");

startActivityForResult(intent, 11);

} else {

Toast.makeText(CameraTest.this,

"sdcard is missing", Toast.LENGTH_LONG)
.show();

}

break;
case 1:
/***
*
* 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的
*/

Intent intent = new Intent();

intent.setType("image/*");

intent.setAction(Intent.ACTION_GET_CONTENT);

startActivityForResult(intent, 12);

break;
}
// Toast.makeText(getApplicationContext(),
// method[which], Toast.LENGTH_SHORT).show();
}
}).create();
ad.show();
}

}
private void uploadFile(String srcPath){
// MyApp ma = (MyApp) getApplicationContext();

String uploadUrl = path;
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
URL url = new URL(uploadUrl);

HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection
.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");

/*this part is for java used
* httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);*/
/*this part is for php used*/
httpURLConnection.setRequestProperty("enctype",
"multipart/form-data;boundary="+boundary);

DataOutputStream dos = new DataOutputStream(
httpURLConnection.getOutputStream());

/*this part is for java used
* dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)+ "\"" + end);
dos.writeBytes(end);*/

Log.i("CAMERA",srcPath);
FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();

dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();

InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result="";
int i=0;
while(i<100){
result= br.readLine();
if(result!=null&&!"".equals(result)){
Log.i("CAMERA", result);//tishi
}
i++;
}
Log.i("CAMERA", br.read()+"---br.read()----");//tishi

Looper.prepare();
Toast.makeText(CameraTest.this, result, Toast.LENGTH_LONG)
.show();
dos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
// setTitle(e.getMessage());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//receive camera message
if(11==requestCode){
Uri uri = data.getData();

if (uri != null) {

photo = BitmapFactory.decodeFile(uri.getPath());
// imageview.setImageBitmap(photo);
}

if (photo == null) {

Bundle bundle = data.getExtras();

if (bundle != null) {

photo = (Bitmap) bundle.get("data");
} else {

Toast.makeText(CameraTest.this,

"get image falure",

Toast.LENGTH_LONG).show();

return;

}

}
imageview.setImageBitmap(photo);
storeImgs(photo);
}

//receive local message
if(12==requestCode){
/**
* 当选择的图片不为空的话,在获取到图片的途径
*/
Uri uri = data.getData();

Log.i("mylog", "local uri = "+ uri);

try {
//MediaStore
String[] pojo = {MediaStore.Images.Media.DATA};

Cursor cursor = this.managedQuery(uri, pojo, null, null,null);

if(cursor!=null)
{
ContentResolver cr = this.getContentResolver();

int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

cursor.moveToFirst();

String path = cursor.getString(colunm_index);
Log.i("CAMERA",path+"-----------------------");

/***

* 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名

* 如果是图片格式的话,那么才可以

*/

if(path.endsWith("jpg")||path.endsWith("png"))

{

picPath = path;

photo = BitmapFactory.decodeStream(cr.openInputStream(uri));

imageview.setImageBitmap(photo);

}else{

}

}else{
String fileName;
String str=uri.toString().substring(0, uri.toString().indexOf("/"));
Log.i("mylog","------"+str);
if("file:".equals(str)){
fileName = uri.toString();
fileName = uri.toString().replace("file://", "");
//替换file://
if(!fileName.startsWith("/mnt")){
//加上"/mnt"头
fileName += "/mnt";
}
imageview.setImageBitmap(BitmapManager.convertToBitmap(fileName, 300, 500));
Log.i("mylog","wrong..------"+fileName);
}

}

} catch (Exception e) {
}
storeImgs(photo);
}

}

private void storeImgs(Bitmap bitmap) {
String pictureDir = "";

FileOutputStream fos = null;

BufferedOutputStream bos = null;

ByteArrayOutputStream baos = null;

try {

baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

byte[] byteArray = baos.toByteArray();

String saveDir = Environment.getExternalStorageDirectory()

+ "/imgs";

File dir = new File(saveDir);

if (!dir.exists()) {

dir.mkdir();
}
//根据系统时间创建名称
filename=Calendar.getInstance().getTimeInMillis()+".jpg";
File file = new File(saveDir, filename);

file.delete();

if (!file.exists()) {

file.createNewFile();

}

fos = new FileOutputStream(file);

bos = new BufferedOutputStream(fos);

bos.write(byteArray);

pictureDir = file.getPath();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (baos != null) {

try {

baos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

if (bos != null) {

try {

bos.close();

} catch (Exception e) {

e.printStackTrace();
}
}
if (fos != null) {

try {

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

// ///
}

需要注意的就是upload方法,在这里。我注释掉的部分是java服务器的代码,需要用时,把php的代码注掉,即可使用。

android 图片上传java,php服务器相关推荐

  1. java图片上传保存至服务器并返回可下载的URL

    java图片上传保存至服务器并返回可下载的URL 1.需求来源 2.解决思路 3.开始干活(直接上代码) 4.总结 1.需求来源 上周要做一个功能,需求是: 微信小程序开发的程序会传一张图片到后台ja ...

  2. moba上传文件到服务器,图片上传到远程服务器上的方法

    图片上传到远程服务器上的方法 内容精选 换一换 将文件上传至Windows云服务器一般会采用MSTSC远程桌面连接的方式.本节为您介绍本地Windows计算机通过远程桌面连接,上传文件至Windows ...

  3. 图片上传压缩android,android 图片上传压缩常见问题分析

    图片的上传与压缩是android经常需要用到的步骤,那么,如何解决上传图片oom问题呢?android 图片上传压缩常见问题分析,希望可以帮助大家更加的了解android 图片方面的困惑. 下面,是我 ...

  4. 将图片上传到FTP服务器

    [FTP服务器] 介绍一个     ftp客户端工具:iis7服务器管理工具 IIs7服务器管理工具可以批量管理ftp站点,同时具备定时上传下载的功能. 作为服务器集成管理器,它最优秀的功能就是批量管 ...

  5. springboot整合easypoi导入带图片excel并将图片上传到FastDFS服务器

    springboot整合easypoi导入带图片excel并将图片上传到FastDFS服务器 1.使用easypoi导入excel 链接: easypoi详细文档. 2.导入easypoi依赖,版本可 ...

  6. 微信公众号调用手机相册并将图片上传到本地服务器

    最近有一个需求,用公众号调用本地相册,并将图片上传到本地服务器(不是微信服务器). 步骤一:引入JS文件 在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq ...

  7. 微信图片消息 服务器故障,解决图片上传到微信服务器后无法显示问题

    标签:attr   ict   viewport   使用   完全   example   cache   ber   copy vue项目里可以添加到app.vue 关于referrer 在页面引 ...

  8. uni-app uni-file-picker文件上传实现拍摄从相册选择获取图片上传文档服务器(H5上传-微信小程序上传)

    前言 最近在使用uni-app写H5移动端,有一个从手机拍摄从相册选择获取图片上传到文档服务器功能. 查阅uni-app发现关于上传图片,uni-file-picker文件上传,uni.chooseI ...

  9. Android图片上传服务器(File格式)

    1.首先我们需要声明几个变量 TreeMap<String, String> paramsMap;. RequestBody requestBody = null; Request req ...

最新文章

  1. import h5py ImportError: DLL load failed: the specified module could not be found
  2. 基于原子探索者stm32f407开发板的ucos-iii+lwip1.4.1的tcp server并发服务器完美解决例程(转)...
  3. Debug 之 VS2010网站生成成功,但是发布失败
  4. linux windows爆音,升级Windows 10后 部分情况下有爆音,杂音,音频卡顿现象
  5. LeetCode 1727. 重新排列后的最大子矩阵(前缀和+排序)
  6. 正确的 zip 压缩与解压代码
  7. Dos命令删除添加新服务
  8. python list(列表)操作用法总结
  9. python随机生成一个地区地址_利用Python生成随机的IP地址
  10. Java编程风格与命名规范整理(转载)
  11. python cox回归_TCGA+biomarker——多因素Cox回归
  12. .deb文件如何安装,Ubuntu下deb安装方法图文详解
  13. 蛇形填数(语言:C语言)
  14. 【ESP 保姆级教程】疯狂传感器篇 —— 案例:UNO/Mega + MQ2烟雾传感器 + MQ3酒精传感器 + MQ7一氧化碳传感器 + OLED
  15. 2015年3月PMP认证考试报名通知
  16. 我跳过的坑-解决linux的输入法问题。
  17. SQL必知必会(一)SQL基础篇
  18. AcWing 1309. 车的放置 (加法原理、乘法原理、组合数排列数的求法、乘法逆元)
  19. 各个流行语言优缺点对比及其适用场景
  20. C#中单例模式的实现

热门文章

  1. html 5入门,HTML5入门
  2. java从内存角度理解类变量_深入理解volatile类型——从Java虚拟机内存模型角度...
  3. oracle 自动化脚本,分享一些非常有用的oracle脚本
  4. 上一家单位离职的原因_员工离职再入职,专项附加扣除该如何变更?
  5. html评论和回复评论_佟丽娅“挑衅”贾玲,评论区晒刘德华合照,贾玲高情商回复佩服...
  6. django启动服务器失败-已解决
  7. 如何使用命令行 群晖_群晖Nas系统篇:拿回root账户权限,适用6.2及以上(7.0)系统...
  8. vue rules 两个输入框不能相等_Vue 学习笔记(二十五):webpack 相关
  9. http接口_基于Python的HTTP接口自动化测试框架实现
  10. 数据结构和算法 D2