package yao.camera.util;





import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import android.graphics.Bitmap;

import android.text.TextUtils;





/**

 * @author wuxifu  图片/文件的上传: Content-Type: multipart/form-data;

 *         boundary=---------------------------114556938680 Content-Length: 210

 * 

 *         -----------------------------114556938680 Content-Disposition:

 *         form-data; name="fileName"; filename="wuxifu.txt" Content-Type:

 *         text/plain

 * 

 *         hello how doyou do -----------------------------114556938680--

 * 

 * 

 */

public class UploadUtils {

public static final String IMAGE_TYPE_PNG = "PNG";

public static final String IMAGE_TYPE_JPG = "JPG";

public static final String end = "\r\n";

public static final String twoHyphens = "--";

public static final String boundary = "*****";

private String url;

private String fileNameKey;





/**

* @param url

* @param fileNameKey

*            name="fileName"之fileName即为fileNameKey,这个取决于后台开发人员的习惯)<form

*            action="uploadFile.php" method="post"

*            enctype="multipart/form-data"> <input type="file"

*            name="fileName"> <input type="submit" value="上传文件"> </form>



*/

public UploadUtils(String url, String fileNameKey) {

super();

this.url = url;

this.fileNameKey = fileNameKey;

}













/**

* @param bitmap

* @param imageType   PNG  JPG

* @param mFileName   hello.jpg    hello.png  须要扩展名

* @param iUpload

*/

public synchronized void uploadBitmap(Bitmap bitmap, String imageType,String mFileName ,IUpload iUpload) {

try {

URL url2 = new URL(url);

HttpURLConnection con = (HttpURLConnection) url2.openConnection();

/* 同意Input、Output,不使用Cache */

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

/* POST方法 */

con.setRequestMethod("POST");

/* setRequestProperty */

con.setRequestProperty("Connection", "Keep-Alive");

con.setRequestProperty("Charset", "UTF-8");

con.setRequestProperty("Content-Type",

"multipart/form-data;boundary=" + boundary);







DataOutputStream ds = new DataOutputStream(con.getOutputStream());





ds.writeBytes(twoHyphens + boundary + end);

ds.writeBytes("Content-Disposition: form-data; " + "name=\""

+ fileNameKey + "\";filename=\"" + mFileName + "\"");

ds.writeBytes(end);// 换行

// 图片类型的确定

if (!TextUtils.isEmpty(imageType)

&& imageType.equals(IMAGE_TYPE_PNG)) {

ds.writeBytes("Content-Type:image/png");

} else {

ds.writeBytes("Content-Type:image/jpeg");

}

ds.writeBytes(end + end);





ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

// 压缩类型的确定

if (!TextUtils.isEmpty(imageType)

&& imageType.equals(IMAGE_TYPE_PNG)) {

bitmap.compress(Bitmap.CompressFormat.PNG, 100,

byteArrayOutputStream);

} else {

bitmap.compress(Bitmap.CompressFormat.JPEG, 100,

byteArrayOutputStream);

}

byte[] byteArray = byteArrayOutputStream.toByteArray();

ds.write(byteArray);

ds.writeBytes(end + end);

ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

/* close streams */

byteArrayOutputStream.close();

ds.flush();

/* 获取提交数据后server返回的内容 */

InputStream is = con.getInputStream();

StringBuffer b = new StringBuffer();

int length = 0;

byte[] buffer = new byte[1024];

while ((length = is.read(buffer)) != -1) {

b.append(new String(buffer, 0, length));

}





/* success */

iUpload.uploadSuccess(b.toString());

/* close */

ds.close();

} catch (Exception e) {

iUpload.uploadFailed(e.toString());

}

}





/**

* @param file  上传文件

* @param iUpload

*/

public synchronized void uploadFile(File file, IUpload iUpload) {

try {

URL url2 = new URL(url);

HttpURLConnection con = (HttpURLConnection) url2.openConnection();

/* 同意Input、Output,不使用Cache */

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

/* post方法*/

con.setRequestMethod("POST");

/* setRequestProperty */

con.setRequestProperty("Connection", "Keep-Alive");

con.setRequestProperty("Charset", "UTF-8");

con.setRequestProperty("Content-Type",

"multipart/form-data;boundary=" + boundary);







DataOutputStream ds = new DataOutputStream(con.getOutputStream());

ds.writeBytes(twoHyphens + boundary + end);

ds.writeBytes("Content-Disposition: form-data; " + "name=\""

+ fileNameKey + "\";filename=\"" + file.getName() + "\"");

ds.writeBytes(end+end);

FileInputStream fStream = new FileInputStream(file);

int bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

int length = -1;

while ((length = fStream.read(buffer)) != -1) {

ds.write(buffer, 0, length);

ds.flush();

}

ds.writeBytes(end + end);

ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

/* close streams */

fStream.close();

ds.flush();

/* 获取提交数据后server返回的内容*/

InputStream is = con.getInputStream();

StringBuffer b = new StringBuffer();

while ((length = is.read(buffer)) != -1) {

b.append(new String(buffer, 0, length));

}

/* success */

iUpload.uploadSuccess(b.toString());

/*close */

ds.close();

} catch (Exception e) {

iUpload.uploadFailed(e.toString());

}

}





public interface IUpload {

void uploadSuccess(String message);





void uploadFailed(String message);

}

}

上传图片/文件到server的更多相关文章

  1. [Ajax] 使用Ajax异步上传图片文件(非Form表单提交)

    通过表单Form提交来上传文件的方式这里就不说了: 下面介绍,通过js中使用ajax异步上传图片文件: 新建一个html页面和一个一般处理程序即可: 涉及思路: //发送2次Ajax请求完成js异步上 ...

  2. 利用webuploader插件上传图片文件,完整前端示例demo,服务端使用SpringMVC接收

    利用WebUploader插件上传图片文件完整前端示例demo,服务端使用SpringMVC接收 Webuploader简介   WebUploader是由Baidu WebFE(FEX)团队开发的一 ...

  3. php上传图片文件常用的几个方法

    1. 前台 <form class="add-form" method="post" action="/person/save" en ...

  4. 利用Spring MVC 上传图片文件

    本文转自:http://amcucn.iteye.com/blog/264457.感谢作者 近日在工作当中,需要用到上传图片的功能,然而自己平时学习的时候只会使用struts的上传功能,但因为项目并没 ...

  5. html+php上传图片文件到服务器

    html+php上传图片文件到服务器 一.html代码 <body> <form action="" method="post" enctyp ...

  6. 工作笔记4.struts2上传文件到server

    本文介绍两种:上传文件到server的方式   一种是提交Form表单:还有一种是ajaxfileupload异步上传. 一.JSP中:     1.提交Form表单 为了能完毕文件上传,我们应该将这 ...

  7. Android端通过HttpURLConnection上传文件到server

    Android端通过HttpURLConnection上传文件到server 一:实现原理 近期在做Androidclient的应用开发,涉及到要把图片上传到后台server中.自己选择了做Sprin ...

  8. ajax上传图片文件

    这里用的是一个隐藏的iframe,这样可以让form表单提交到这个iframe里面,用户就看不到页面的刷新了 前段时间在解决ajax上传文件时折腾了好一阵.直接用$.post上传文本信息肯定是没有问题 ...

  9. ionic新手教程第三课-在项目中使用requirejs分离controller文件和server文件

    继上篇教程中提到的,我们新建一个简单的tabs类型的Ionic项目. 依据文件夹文件我们知道,系统自己主动创建了一个controller文件和server文件,而且把全部的控制器和服务都写到这两个文件 ...

随机推荐

  1. Leetcode33--->Search in Rotated Sorted Array(在旋转数组中找出给定的target值的位置)

    题目: 给定一个旋转数组,但是你不知道旋转位置,在旋转数组中找出给定target值出现的位置:你可以假设在数组中没有重复值出现 举例: (i.e., 0 1 2 4 5 6 7 might becom ...

  2. Python-函数参数的传递

    作者:Vamei 出处:http://www.cnblogs.com/vamei,感谢博主的分享, python的函数参数传递有这样的几种形式: 1.位置传递 2.关键字传递 3.参数默认值传递 4. ...

  3. linux内核代码注释 赵炯 第三章引导启动程序

    linux内核代码注释 第三章引导启动程序 boot目录中的三个汇编代码文件   bootsect.s和setup.s采用近似intel的汇编语法,需要8086汇编器连接器as86和ld86 head ...

  4. 2017"百度之星"程序设计大赛 - 初赛(A)

    小C的倍数问题  Accepts: 1990  Submissions: 4931  Time Limit: 2000/1000 MS (Java/Others)  Memory Limit: 327 ...

  5. VirtualBox Host-only Adapter,Failed to create the host-only adapter 转

    不用重装VirtualBox,安装虚拟网卡 今天使用VirtualBox的host-only模式,因为之前把网络连接卸载,这次出现的各种错误. Failed to create the host-on ...

  6. 【bzoj1163/bzoj1339】[Baltic2008]Mafia 网络流最小割

    题目描述 匪徒准备从一个车站转移毒品到另一个车站,警方准备进行布控. 对于每个车站进行布控都需要一定的代价,现在警方希望使用最小的代价控制一些车站,使得去掉这些车站后,匪徒无法从原定的初始点到达目标点 ...

  7. Codeforces 903F Clear the Matrix

    题目大意 考虑一个 $4$ 行 $n$ ($4\le n\le 1000$)列的矩阵 $f$,$f$ 中的元素为 * 或 . . 对 $f$ 进行若干次如下变换: 将一个 $k\times k$($1 ...

  8. 【CCF】有趣的数 数位dp

    [思路] dp[i][j]表示前i个数为第j种状态,考虑6种状态 0: 出现且仅出现 2 1: 出现且仅出现 2 0 2: 出现且仅出现 2 3 3: 出现且仅出现 2 0 1 4: 出现且仅出现 2 ...

  9. java面试题之什么是多线程上下文切换

    多线程会共同使用一组计算机上的CPU,而线程数大于给程序分配的CPU数量时,为了让各个线程都有执行的机会,就需要轮流使用CPU.不同的线程切换使用CPU发生的数据切换等就是上下文切换

  10. nvm、node、npm安装以及pycharm配置eslint

    nvm.node.npm之间的区别 1. nvm的官方叫法:nodejs版本管理工具. nvm相当于是家长,一个家长可以管理多个孩子. 也就是说:一个nvm可以管理很多node版本和npm版本. 2. ...