我想添加上传图片大小的限制(目前图片上传到服务器)。
当有人从 SD 卡获取图像或从相机捕获图像时,我想向用户显示它上传的最大文件大小的消息 - 即 500kb 或者我可以将图像调整为更小的尺寸。例如,将 1mb 图像调整为 400-500kb(如 Facebook)。
这是我从 SD 卡获取图像或从相机捕获图像后实现的示例代码。
FileConnection file = (FileConnection)Connector.open(url);
if(file.exists())
{
try{
String fileName = url .substring(url.lastIndexOf('/') + 1);
//String fileName = url ;
Dialog.alert("fileName " + fileName);
InputStream inputStream = file.openInputStream();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=1024;
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
byte[] imagedata=bos.toByteArray();
Dialog.alert("Url " + Url + " Image Data Byte " + imagedata);
HttpConnection conn = (HttpConnection) Connector.open(Url, Connector.READ_WRITE);
conn.setRequestMethod(HttpConnection.POST);
String boundary = "Some_Unique_Text_Also_Alphanumeric";
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,
HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA
+ ";boundary=" + boundary);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,
String.valueOf(imagedata.length));
conn.setRequestProperty("x-rim-transcode-content", "none");
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream finalOut = conn.openOutputStream();
String newLine = "\r\n";
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write(newLine.getBytes());
String contDisp = "Content-Disposition:form-data;name=\"image\";fileName=\"Image.jpg\"";
String contEnc = "Content-Transfer-Encoding: binary";
String contentType = "Content-Type:image/jpeg";
out.write(contDisp.getBytes());
out.write(newLine.getBytes());
out.write(contentType.getBytes());
out.write(newLine.getBytes());
out.write(contEnc.getBytes());
out.write(newLine.getBytes());
out.write(newLine.getBytes());
out.write(imagedata);
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write("--".getBytes());
out.write(newLine.getBytes());
finalOut.write(out.toByteArray());
out.flush();
out.close();
finalOut.flush();
finalOut.close();
InputStream instream=conn.openInputStream();
int ch=0;
StringBuffer buffesr=new StringBuffer();
while((ch=instream.read())!=-1)
{
buffesr.append((char)ch);
Dialog.alert("Uploaded");
}
}
catch (Exception e) {
Dialog.alert("Exception " + e);
}
}
有什么帮助吗??