上传图片/文件到server

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 = " ";
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);
}


}


原文地址:https://www.cnblogs.com/yfceshi/p/6852747.html