|
package ai.pai.lensman.service;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.android.common.utils.LogHelper;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class PhotoUploadUtils {
private URL url;
private DataOutputStream ds;
private HttpURLConnection conn;
private Map<String, File> fileparams = new HashMap<String, File>();
private Map<String, String> textParams = new HashMap<String, String>();
private static final String boundary = "----WebKitFormBoundaryE19zNvXGzXaLvS5C";
public static final int UPLOAD_PHOTO_WIDTH = 1280;
public static final int UPLOAD_PHOTO_HEIGHT = 1280;
public PhotoUploadUtils(String url) throws Exception {
this.url = new URL(url);
}
//增加一个普通字符串数据到form表单数据中
public void addTextParameter(String name, String value) {
textParams.put(name, value);
}
//增加一个文件到form表单数据中
public void addFileParameter(String name, File value) {
fileparams.put(name, value);
}
// 清空所有已添加的form表单数据
public void clearAllParameters() {
textParams.clear();
fileparams.clear();
}
// 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
public byte[] send() throws Exception {
initConnection();
conn.connect();
ds = new DataOutputStream(conn.getOutputStream());
writeFileParams();
writeStringParams();
paramsEnd();
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
return out.toByteArray();
}
//文件上传的connection的一些必须设置
private void initConnection() throws Exception {
conn = (HttpURLConnection) this.url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
}
//普通字符串数据
private void writeStringParams() throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"\r\n");
ds.writeBytes("\r\n");
ds.writeBytes(encode(value) + "\r\n");
}
}
//文件数据
private void writeFileParams() throws Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
File value = fileparams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + encode(value.getName()) + "\"\r\n");
ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
ds.writeBytes("\r\n");
byte[] bmp = getBitmapBytes(value);
ds.write(bmp);
LogHelper.d("czy","upload final file length="+bmp.length);
LogHelper.d("czy","Upload bitmap size:"+bmp.length);
ds.writeBytes("\r\n");
// saveUploadFile(value,bmp);
}
}
//获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
private String getContentType(File file) throws Exception {
return "image/jpeg";
}
private void saveUploadFile(File file,byte[] bmp){
String dirPath = Constants.APP_UPLOAD_DIR;
try{
File uploadFile = new File(dirPath,file.getName());
FileOutputStream fos = new FileOutputStream(uploadFile);
fos.write(bmp);
fos.close();
LogHelper.d("czy","upload file save path = "+uploadFile.getAbsolutePath());
Bitmap finalBmp = BitmapFactory.decodeFile(uploadFile.getAbsolutePath());
LogHelper.dfile("czy","照片上传bitmap质量压缩后,宽 = "+finalBmp.getWidth()+"高="+finalBmp.getHeight()+"文件大小="+uploadFile.length()+"字节");
LogHelper.dfile("czy","\n----------------------------------------------------\n");
}catch (Exception e){
e.printStackTrace();
}
}
//把文件转换成字节数组
private byte[] getBitmapBytes(File f) throws Exception {
int uploadWidth = UPLOAD_PHOTO_WIDTH;
int uploadHeight = UPLOAD_PHOTO_HEIGHT;
int uploadQuality = 90;
LogHelper.d("czy","upload default width = "+uploadWidth+"uploadQuality="+uploadQuality);
try{
File file = new File(Constants.APP_UPLOAD_CONFIG_PATH);
if(file.exists()){
BufferedReader reader = new BufferedReader(new FileReader(file));
uploadHeight = Integer.parseInt(reader.readLine());
uploadWidth = uploadHeight;
uploadQuality = Integer.parseInt(reader.readLine());
reader.close();
}else{
file.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(String.valueOf(uploadHeight));
writer.write("\r\n");
writer.write(String.valueOf(uploadQuality));
writer.write("\r\n");
writer.close();
}
}catch (Exception e){
e.printStackTrace();
}
Bitmap bmp = ImageUtils.decodeBitmapWithSize(f.getAbsolutePath(), uploadWidth,uploadHeight);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, uploadQuality, baos);
return baos.toByteArray();
}
//把文件转换成字节数组
private byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
//添加结尾数据
private void paramsEnd() throws Exception {
ds.writeBytes("--" + boundary + "--" + "\r\n");
ds.writeBytes("\r\n");
}
// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
private String encode(String value) throws Exception {
return URLEncoder.encode(value, "UTF-8");
}
}
|