上傳圖片/文件到服務器

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();
/* 獲取提交數據後服務器返回的內容 */
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();
/* 獲取提交數據後服務器返回的內容*/
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);
}


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章