當前位置:首頁 » 文件管理 » android拍照上傳到伺服器

android拍照上傳到伺服器

發布時間: 2022-06-21 07:35:19

⑴ Android 上傳圖片到伺服器

final Map<String, String> params = new HashMap<String, String>();
params.put("send_userId", String.valueOf(id));
params.put("send_email", address);
params.put("send_name", name);
params.put("receive_email", emails);

final Map<String, File> files = new HashMap<String, File>();
files.put("uploadfile", file);

final String request = UploadUtil.post(requestURL, params, files);

⑵ android怎樣上傳圖片到伺服器

界面很簡單,點擊 【選擇圖片】,從圖庫里選擇圖片,顯示到下面的imageview里,點擊上傳,就會上傳到指定的伺服器

布局文件:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="選擇圖片"
android:id="@+id/selectImage"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="上傳圖片"
android:id="@+id/uploadImage"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
/>
</LinearLayout>

Upload Activity:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

public class Upload extends Activity implements OnClickListener {
private static String requestURL = "http://192.168.1.212:8011/pd/upload/fileUpload.do";
private Button selectImage, uploadImage;
private ImageView imageView;

private String picPath = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);

selectImage = (Button) this.findViewById(R.id.selectImage);
uploadImage = (Button) this.findViewById(R.id.uploadImage);
selectImage.setOnClickListener(this);
uploadImage.setOnClickListener(this);

imageView = (ImageView) this.findViewById(R.id.imageView);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectImage:
/***
* 這個是調用android內置的intent,來過濾圖片文件 ,同時也可以過濾其他的
*/
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
break;
case R.id.uploadImage:
if (picPath == null) {

Toast.makeText(Upload.this, "請選擇圖片!", 1000).show();
} else {
final File file = new File(picPath);

if (file != null) {
String request = UploadUtil.uploadFile(file, requestURL);
uploadImage.setText(request);
}
}
break;
default:
break;
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
/**
* 當選擇的圖片不為空的話,在獲取到圖片的途徑
*/
Uri uri = data.getData();
Log.e(TAG, "uri = " + uri);
try {
String[] pojo = { MediaStore.Images.Media.DATA };

Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null) {
ContentResolver cr = this.getContentResolver();
int colunm_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(colunm_index);
/***
* 這里加這樣一個判斷主要是為了第三方的軟體選擇,比如:使用第三方的文件管理器的話,你選擇的文件就不一定是圖片了,
* 這樣的話,我們判斷文件的後綴名 如果是圖片格式的話,那麼才可以
*/
if (path.endsWith("jpg") || path.endsWith("png")) {
picPath = path;
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
imageView.setImageBitmap(bitmap);
} else {
alert();
}
} else {
alert();
}

} catch (Exception e) {
}
}

super.onActivityResult(requestCode, resultCode, data);
}

private void alert() {
Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
.setMessage("您選擇的不是有效的圖片")
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
picPath = null;
}
}).create();
dialog.show();
}

}

這個才是重點 UploadUtil:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 超時時間
private static final String CHARSET = "utf-8"; // 設置編碼
/**
* 上傳文件到伺服器
* @param file 需要上傳的文件
* @param RequestURL 請求的rul
* @return 返回響應的內容
*/
public static int uploadFile(File file, String RequestURL) {
int res=0;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識 隨機生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型

try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流
conn.setDoOutput(true); // 允許輸出流
conn.setUseCaches(false); // 不允許使用緩存
conn.setRequestMethod("POST"); // 請求方式
conn.setRequestProperty("Charset", CHARSET); // 設置編碼
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);

if (file != null) {
/**
* 當文件不為空時執行上傳
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 這里重點注意: name裡面的值為伺服器端需要key 只有這個key 才可以得到對應的文件
* filename是文件的名字,包含後綴名
*/

sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 獲取響應碼 200=成功 當響應成功,獲取響應的流
*/
res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
} else {
Log.e(TAG, "request error");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}

⑶ Android打開系統相冊返回一張圖片,如何將返回的圖片上傳到Tomcat伺服器中

文件上傳需要用到HttpClient,打開系統相冊需要通過內容提供者調用android相冊或者文件管理器(源代碼查看附件)關於HttpClient的文件上傳HttpClient相比傳統JDK自帶的URLConnection,增加了易用性和靈活性(具體區別,日後我們再討論),它不僅是客戶端發送Http請求變得容易,而且也方便了開發人員測試介面(基於Http協議的),即提高了開發的效率,也方便提高代碼的健壯性。因此熟練掌握HttpClient是很重要的必修內容,掌握HttpClient後,相信對於Http協議的了解會更加深入。

一、HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,並且它支持HTTP協議最新的版本和建議。HttpClient已經應用在很多的項目中,比如Apache Jakarta上很著名的另外兩個開源項目Cactus和HTMLUnit都使用了HttpClient。

二、特性

1. 基於標准、純凈的java語言。實現了Http1.0和Http1.1

2. 以可擴展的面向對象的結構實現了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS協議。

4. 通過Http代理建立透明的連接。

5. 利用CONNECT方法通過Http代理建立隧道的https連接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos認證方案。

7. 插件式的自定義認證方案。

8. 便攜可靠的套接字工廠使它更容易的使用第三方解決方案。

9. 連接管理器支持多線程應用。支持設置最大連接數,同時支持設置每個主機的最大連接數,發現並關閉過期的連接。

10. 自動處理Set-Cookie中的Cookie。

11. 插件式的自定義Cookie策略。

12. Request的輸出流可以避免流中內容直接緩沖到socket伺服器。

13. Response的輸入流可以有效的從socket伺服器直接讀取相應內容。

14. 在http1.0和http1.1中利用KeepAlive保持持久連接。

15. 直接獲取伺服器發送的response code和 headers。

16. 設置連接超時的能力。

17. 實驗性的支持http1.1 response caching。

18. 源代碼基於Apache License 可免費獲取。


三、使用方法

使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可。

1.創建HttpClient對象。

2.創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。

3.如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。

4.調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。

5.調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取伺服器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了伺服器的響應內容。程序可通過該對象獲取伺服器的響應內容。

6.釋放連接。無論執行方法是否成功,都必須釋放連接

⑷ 使用android上傳圖片到伺服器,並且把圖片保存到伺服器的某個文件夾

有兩種方法,第一,把你的圖片轉成位元組流,然後用post方法把位元組流傳到服務端,然後服務端接收到位元組流之後,開啟一個線程把它重新壓縮成圖片,保存在某個文件夾下面。
第二,開啟一個線程,用socket直接把圖片放到stream中傳到服務端,服務端接收後保存到文件夾下。

⑸ android開發怎麼實現拍照上傳

這個其實是一個很泛的問題

我大致說下我的思路:

  1. 用startactivityforresult方法調用系統的攝像頭,隨便拍張照片,把照片保存在某一目錄下面

  2. 點擊完成後,會在onactivityresult中,根據目錄的地址,再把這目錄下面的資源得轉換為文件,接著通過介面進行提交。提交成功後,後台返回一個URL。

  3. 通過這個URL,運用imageload(第三方插件)顯示圖片

⑹ android將圖片上傳到伺服器資料庫的欄位里,用什麼方法

1,配置webservice 接收上傳圖片以及保存到的位置,我用tableName/colName/id.jpg 來當存儲路徑
2,終端發送上傳請求,接收圖片保存到伺服器
3,上傳結束後,將圖片存入資料庫欄位里,刪除伺服器對應圖片。

代碼很多,自己找

⑺ android上傳圖片到伺服器,求伺服器那邊和android的Activity的完整代碼。

伺服器端servlet代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//獲取輸入流,是HTTP協議中的實體內容
ServletInputStream sis=request.getInputStream();

File file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+0+".jpg");
for (int imgnum = 0;file.exists();imgnum++)
{
file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+imgnum+".jpg");
}
//緩沖區
byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream(file);
int len=sis.read(buffer, 0, 1024);
//把流里的信息循環讀入到文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}

android客戶端代碼:
public static void uploadFile(String imageFilePath)
{
String actionUrl = "http://192.168.1.32:8080/UploadServer/ImageServlet";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();

con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.setRequestMethod("POST");

DataOutputStream ds = new DataOutputStream(con.getOutputStream());
File file = new File(imageFilePath);

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

fStream.close();
ds.flush();

InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}

ds.close();
}
catch(Exception e)
{
e.printStackTrace();
}

}

⑻ android怎麼將圖片傳送到伺服器,然後將圖片保存在mysql資料庫中

一般資料庫中是不保存圖片的,保存的是圖片存放路徑,圖片放到文件夾中,如果放到資料庫中資料庫會很大,影響讀取速度。
如果想放就把欄位定義為如:`img` longblob;
然後就可以讀取文件流 存儲到資料庫中了就可以了

⑼ android中如何上傳圖片到ftp伺服器

在安卓環境下可以使用,在java環境下也可以使用,已經在Java環境下實現了功能,然後移植到了安卓手機上,其它都是一樣的。

[java] view plain
package com.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FileTool {

/**
* Description: 向FTP伺服器上傳文件
*
* @param url
* FTP伺服器hostname
* @param port
* FTP伺服器埠
* @param username
* FTP登錄賬號
* @param password
* FTP登錄密碼
* @param path
* FTP伺服器保存目錄,是linux下的目錄形式,如/photo/
* @param filename
* 上傳到FTP伺服器上的文件名,是自己定義的名字,
* @param input
* 輸入流
* @return 成功返回true,否則返回false
*/
public static boolean uploadFile(String url, int port, String username,
String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();

try {
int reply;
ftp.connect(url, port);// 連接FTP伺服器
// 如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);

input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}

// 測試
public static void main(String[] args) {

FileInputStream in = null ;
File dir = new File("G://pathnew");
File files[] = dir.listFiles();
if(dir.isDirectory()) {
for(int i=0;i<files.length;i++) {
try {
in = new FileInputStream(files[i]);
boolean flag = uploadFile("17.8.119.77", 21, "android", "android",
"/photo/", "412424123412341234_20130715120334_" + i + ".jpg", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

}
}

以上為java代碼,下面是android代碼。

[java] view plain
package com.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new uploadThread().start();
}

class uploadThread extends Thread {
@Override
public void run() {
FileInputStream in = null ;
File dir = new File("/mnt/sdcard/DCIM/Camera/test/");
File files[] = dir.listFiles();
if(dir.isDirectory()) {
for(int i=0;i<files.length;i++) {
try {
in = new FileInputStream(files[i]);
boolean flag = FileTool.uploadFile("17.8.119.77", 21, "android", "android",
"/", "412424123412341234_20130715120334_" + i + ".jpg", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
}

熱點內容
建立雲存儲 發布:2024-05-03 21:04:03 瀏覽:74
socket編程php 發布:2024-05-03 20:12:50 瀏覽:207
坦洲郵政局可以解壓嗎 發布:2024-05-03 20:09:55 瀏覽:732
二級程序編譯答案 發布:2024-05-03 18:41:35 瀏覽:654
領動自動精英版是哪個配置 發布:2024-05-03 18:37:30 瀏覽:151
java編譯器中cd什麼意思 發布:2024-05-03 18:36:00 瀏覽:390
傳奇伺服器如何刷錢 發布:2024-05-03 18:36:00 瀏覽:978
安卓版twitter怎麼注冊 發布:2024-05-03 18:28:05 瀏覽:894
Python邏輯優先順序 發布:2024-05-03 18:26:14 瀏覽:268
linux查看svn密碼 發布:2024-05-03 18:12:47 瀏覽:805