服务器端(Servlet的)code在Android的上传图片 [英] Server side(Servlet) code for upload image in android
本文介绍了服务器端(Servlet的)code在Android的上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何保存使用Java在我的服务器的特定位置如C Android设备上传的图片:\\ Program Files文件\\ Tomcat的7.0 \\图片。
这里是我的客户端code
公共静态无效uploadPictureToServer(字符串i_file)抛出ClientProtocolException,IOException异常{
位图bitmapOrg = BitmapFactory.de codeFILE(i_file); ByteArrayOutputStream宝=新ByteArrayOutputStream(); bitmapOrg.com preSS(Bitmap.Com pressFormat.JPEG,90,包); 字节[] BA = bao.toByteArray(); 字符串BA1 = Base64.en code(BA); ArrayList的<&的NameValuePair GT; namevaluepairs中新= ArrayList的<&的NameValuePair GT;(); nameValuePairs.add(新BasicNameValuePair(形象,BA1)); 尝试{ HttpClient的HttpClient的=新DefaultHttpClient(); HttpPost httppost =新 HttpPost(Constant.uploadImage); httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中)); HTT presponse响应= httpclient.execute(httppost); HttpEntity实体= response.getEntity(); 是= entity.getContent(); }赶上(例外五){ Log.e(log_tag,在HTTP连接错误+ e.toString()); }
解决方案
工作code对我来说:
doFileUpload功能:
私人无效doFileUpload(){
HttpURLConnection的康恩= NULL;
DataOutputStream类DOS = NULL;
DataInputStream以inStream中= NULL;
字符串exsistingFileName =/sdcard/six.3gp;
//这是这个地方,你做错了什么。
字符串lineEnd =\\ r \\ n;
串twoHyphens = - ;
字符串边界=*****;
INT读取动作,方bytesAvailable,缓冲区大小;
字节[]缓冲区;
INT MAXBUFFERSIZE = 1 * 1024 * 1024;
字符串urlString =http://192.168.1.5/upload.php;
尝试
{
Log.e(MediaPlayer的,内部第二种方法);
的FileInputStream的FileInputStream =新的FileInputStream(新文件(exsistingFileName));
网址URL =新的URL(urlString);
康恩=(HttpURLConnection类)url.openConnection();
conn.setDoInput(真);
//允许输出
conn.setDoOutput(真);
//不要使用缓存副本。
conn.setUseCaches(假);
//使用POST方法。
conn.setRequestMethod(POST);
conn.setRequestProperty(连接,保持活动);
conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);
DOS =新的DataOutputStream类(conn.getOutputStream());
dos.writeBytes(twoHyphens +边界+ lineEnd);
dos.writeBytes(内容处置:表格数据;名称= \\UploadedFile的\\;文件名= \\+ exsistingFileName +\\+ lineEnd);
dos.writeBytes(lineEnd);
Log.e(MediaPlayer的,头信息);
参考bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
缓冲区=新的字节[缓冲区大小]
读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
而(读取动作大于0)
{
dos.write(缓冲液,0,缓冲区大小);
参考bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);
在的BufferedReader =新的BufferedReader(新的InputStreamReader(conn.getInputStream()));
串inputLine;
而((inputLine = in.readLine())!= NULL)
tv.append(inputLine);
//关闭流
Log.e(MediaPlayer的,文件写入);
fileInputStream.close();
dos.flush();
dos.close();
}
赶上(MalformedURLException的前)
{
Log.e(MediaPlayer的,错误:+ ex.getMessage(),除息);
}
赶上(IOException异常IOE)
{
Log.e(MediaPlayer的,错误:+ ioe.getMessage(),IOE);
} // ------------------读取服务器响应
尝试{
inStream中=新DataInputStream所(conn.getInputStream());
字符串str;
而((海峡= inStream.readLine())!= NULL)
{
Log.e(MediaPlayer的,服务器响应+ STR);
}
/ *而((海峡= inStream.readLine())!= NULL){ } * /
inStream.close();
}
赶上(IOException异常ioex){
Log.e(MediaPlayer的,错误:+ ioex.getMessage(),ioex);
}
}
upload.php的
< PHPmove_uploaded_file($ _ FILES ['UploadedFile的'] ['tmp_name的值'],./upload/\".$_FILES[\"uploadedfile\"][\"name]);mysql_connect(localhost的根,);
mysql_select_db(聊天);
如果(使用isset($ _ REQUEST ['味精']))
{
$ a = $ _REQUEST ['味精'];
$ SQL =INSERT INTO上传(图)VALUES('$ A');
的mysql_query($的SQL);
}
?>
how to save the image uploaded from a android device using java in my server to a specific location like C:\Program Files\Tomcat 7.0\Images. here is my client side code
public static void uploadPictureToServer(String i_file) throws ClientProtocolException,IOException {
Bitmap bitmapOrg = BitmapFactory.decodeFile(i_file);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encode(ba);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(Constant.uploadImage);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
解决方案
Working Code for me :
doFileUpload Function :
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/six.3gp";
// Is this the place are you doing something wrong.
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://192.168.1.5/upload.php";
try
{
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
tv.append(inputLine);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
/*while((str = inStream.readLine()) !=null ){
}*/
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
upload.php
<?php
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./upload/".$_FILES["uploadedfile"]["name"]);
mysql_connect("localhost","root","");
mysql_select_db("chat");
if(isset($_REQUEST['msg']))
{
$a = $_REQUEST['msg'];
$sql = "INSERT INTO upload(image)VALUES('$a')";
mysql_query($sql);
}
?>
这篇关于服务器端(Servlet的)code在Android的上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文