導航:首頁 > 操作系統 > android上傳圖片到伺服器

android上傳圖片到伺服器

發布時間:2022-01-24 04:12:31

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

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

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

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

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

❹ 從android手機上傳到伺服器的圖片如何立即返回在手機控制項上顯示

你需要寫一個方法,讀取網路圖片,在上傳操作完成後,調用這個方法,
這個是我經常用的讀取網路圖片的方法,你參考一下:
//url為圖片的網路地址,
public static Bitmap getImg(String url)
{
URL imgurl = null;
Bitmap bitmap = null;
try
{
imgurl = new URL(url);

}
catch(MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn = (HttpURLConnection)imgurl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
conn.disconnect();
}catch(IOException e)
{
e.printStackTrace();
}
return bitmap;

}

然後在要顯示的的activity里,將這個方法傳給imageview就可以了
imageview.setImageBitmap(MainActivity.getImg(url));

❺ android中數據上傳到伺服器怎麼實現

伺服器端寫個servlet,然後在doPost()方法里處理客戶端上傳的文件,大概代碼: DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 1024); // 設置最多隻允許在內存中存儲的數據, 單位:位元組 factory.setRepository(cachepath); // 設置一旦文件大小超過設定值時數據存放的目錄 ServletFileUpload srvFileUpload = new ServletFileUpload(factory); srvFileUpload.setSizeMax(1024 * 1024 * 1024); // 設置允許用戶上傳文件大小, 單位:位元組 // 開始讀取上傳信息 List fileItems = null; try { fileItems = srvFileUpload.parseRequest(request); } catch (Exception e) { System.out.println("獲取上傳信息。。。。。。失敗"); } // 依次處理每個上傳的文件 Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 忽略其他不是文件域的所有表單信息 if (!item.isFormField()) { // 取出文件域的所有表單信息 } else { // 取出不是文件域的所有表單信息 } }

❻ 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里的圖片怎樣上傳到伺服器並返回顯示在手機上求具體的代碼急用!!!

這個圖片存放的位置是根據你的圖片來源而定的。一般是放在sdcard下的某個目錄下的,我基本看明白你寫的需求。我來給你說下思路:服務端(android手機)這邊需要寫個工具類,來遍歷SD卡下的文件,只顯示jpg和png的圖片。主類中有個按鈕來添加圖片,還有一個按鈕是用來上傳圖片,然後寫個監聽,用來接收服務端發回的消息。文件的傳輸就不用我細說了吧...服務端這邊寫個監聽來接收客戶端發來的消息,保存發過來的數據流。至於手機上能顯示這張圖片,只要在寫個imageview,把圖片資源載入上就ok啦,你可以去網上搜索一下「sd上的文件上傳」,有很多類似的文章和代碼,可供學習的,有什麼不懂的再問吧^_^

❽ 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怎麼在伺服器和客戶端之間傳輸圖片

本地獲取服務端的話,是服務端返回一個url,然後本地載入網路圖片bitmap流,然後載入到imageview里,服務端的話,就是本地圖片上傳了

閱讀全文

與android上傳圖片到伺服器相關的資料

熱點內容
阿里雲伺服器中沒有apt 瀏覽:606
發送信息需要用戶加密嗎 瀏覽:634
六年級分數乘分數有幾種演算法 瀏覽:295
到哪裡查自己的app賬號 瀏覽:117
光大app點擊哪裡可以查年費 瀏覽:875
加密狗軟體先安裝還是先先後順序 瀏覽:351
柱頭加密區箍筋間距一般多少 瀏覽:681
美團商家版本服務中心在app哪裡 瀏覽:987
androidgps調試 瀏覽:821
比心app怎麼下載官方 瀏覽:48
安卓怎麼隱藏手機上的app 瀏覽:580
hp光纖交換機命令 瀏覽:896
pythonhive導入數據 瀏覽:673
安卓手機屏幕按住一直抖怎麼辦 瀏覽:195
壓縮率公式 瀏覽:321
藍虎app怎麼下載 瀏覽:615
周易江湖pdf 瀏覽:861
java取主機名 瀏覽:367
python轉為unicode 瀏覽:296
米家app門鎖怎麼解綁 瀏覽:330