有個html頁面,用html裡面自帶的
一、Android端實現文件上傳1、新建一個Android項目命名為androidUpload。2、新建FormFile類,用來封裝文件信息。)、新建SocketHttpRequester類,封裝上傳文件到伺服器代碼。4、新建MainActivity類,實現每隔5秒上傳一次。5、修改清單文件。
二、伺服器端用來獲取Android端上傳過來的文件信息1、新建一個web項目命名為upload。注意:記得加入struts2jar包。2、新建action類,命名為UploadAction。3、配置struts.xml。4、配置web.xml。
② android中如何上傳圖片到FTP伺服器
android客戶端實現FTP文件需要用到 commons-net-3.0.1.jar
先將jar包復制到android libs目錄下
復制以下實現代碼
以下為實現代碼:
/**
* 通過ftp上傳文件
* @param url ftp伺服器地址 如:
* @param port 埠如 :
* @param username 登錄名
* @param password 密碼
* @param remotePath 上到ftp伺服器的磁碟路徑
* @param fileNamePath 要上傳的文件路徑
* @param fileName 要上傳的文件名
* @return
*/
public String ftpUpload(String url, String port, String username,String password, String remotePath, String fileNamePath,String fileName) {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
String returnMessage = "0";
try {
ftpClient.connect(url, Integer.parseInt(port));
boolean loginResult = ftpClient.login(username, password);
int returnCode = ftpClient.getReplyCode();
if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登錄成功
ftpClient.makeDirectory(remotePath);
// 設置上傳目錄
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.enterLocalPassiveMode();
fis = new FileInputStream(fileNamePath + fileName);
ftpClient.storeFile(fileName, fis);
returnMessage = "1"; //上傳成功
} else {// 如果登錄失敗
returnMessage = "0";
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客戶端出錯!", e);
} finally {
//IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("關閉FTP連接發生異常!", e);
}
}
return returnMessage;
}
③ android 怎麼寫上傳圖片代碼
請問圖片是放在android手機的哪個地方,要在android手機怎麼顯示返回呢,主類中有個按鈕來添加圖片,還有一個按鈕是用來上傳圖片,然後寫個監聽,
④ 安卓如何在後台上傳圖片等資料
public class EX08_11 extends Activity
{
/* 變數聲明
* newName:上傳後在伺服器上的文件名稱
* uploadFile:要上傳的文件路徑
* actionUrl:伺服器對應的程序路徑 */
// private String newName="345444.jpg";
private String uploadFile="/sdcard/345444.jpg";
private String actionUrl="http://*********/upload.PHP";
private TextView mText1;
private TextView mText2;
private Button mButton;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText1 = (TextView) findViewById(R.id.myText2);
mText1.setText("文件路徑:/n"+uploadFile);
mText2 = (TextView) findViewById(R.id.myText3);
mText2.setText("上傳網址:/n"+actionUrl);
/* 設定mButton的onClick事件處理 */
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
/* 上傳文件吹Server的method */
private void uploadFile()
{
// String end = "/r/n";
// String twoHyphens = "--";
String boundary = "*****";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允許Input、Output,不使用Cache */
// con.setReadTimeout(5 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 設定傳送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("enctype",
"multipart/form-data;boundary="+boundary);
/* 設定DataOutputStream */
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
/*ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " +
"name=/"file1/";filename=/"" +
newName +"/"" + end);
ds.writeBytes(end); */
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(uploadFile);
/* 設定每次寫入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 從文件讀取數據到緩沖區 */
while((length = fStream.read(buffer)) != -1)
{
/* 將數據寫入DataOutputStream中 */
ds.write(buffer, 0, length);
}
// ds.writeBytes(end);
// ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response內容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}
/* 將Response顯示於Dialog */
showDialog(b.toString().trim());
/* 關閉DataOutputStream */
ds.close();
}
catch(Exception e)
{
showDialog(""+e);
}
}
/* 顯示Dialog的method */
private void showDialog(String mess)
{
new AlertDialog.Builder(EX08_11.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("確定",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}
PHP代碼
[php] view plain
$data = file_get_contents('php://input');
$handle = fopen($_SERVER['DOCUMENT_ROOT'].'/image/345444.jpg', 'w');
if ($handle)
{
fwrite($handle,$data);
fclose($handle);
echo "success";
}
⑤ android如何實現圖片批量上傳
首先,以下架構下的批量文件上傳可能會失敗或者不會成功:
1.android客戶端+springMVC服務端:服務端採用org.springframework.web.multipart.MultipartHttpServletRequest作為批量上傳接收類,這種搭配下的批量文件上傳會失敗,最終服務端只會接受到一個文件,即只會接受到第一個文件。可能因為MultipartHttpServletRequest對servlet原本的HttpServletRequest類進行封裝,導致批量上傳有問題。
2.android客戶端+strutsMVC服務端:
上傳成功的方案:
採用android客戶端+Servlet(HttpServletRequest)進行文件上傳。
Servlet端代碼如下:
[java] view plainprint?
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
System.out.println("表單參數名:" + item.getFieldName() + ",表單參數值:" + item.getString("UTF-8"));
}
else
{
if (item.getName() != null && !item.getName().equals(""))
{
System.out.println("上傳文件的大小:" + item.getSize());
System.out.println("上傳文件的類型:" + item.getContentType());
// item.getName()返回上傳文件在客戶端的完整路徑名稱
System.out.println("上傳文件的名稱:" + item.getName());
File tempFile = new File(item.getName());
// 上傳文件的保存路徑
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上傳文件成功!");
} else
{
request.setAttribute("upload.message", "沒有選擇上傳文件!");
}
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
request.setAttribute("upload.message", "上傳文件失敗!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
android端代碼如下:
[java] view plainprint?
public class SocketHttpRequester {
/**
*多文件上傳
* 直接通過HTTP協議提交數據到伺服器,實現如下面表單提交功能:
* <FORM METHOD=POST ACTION="http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype="multipart/form-data">
<INPUT TYPE="text" NAME="name">
<INPUT TYPE="text" NAME="id">
<input type="file" name="imagefile"/>
<input type="file" name="zip"/>
</FORM>
* @param path 上傳路徑(註:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.iteye.cn或http://192.168.1.101:8083這樣的路徑測試)
* @param params 請求參數 key為參數名,value為參數值
* @param file 上傳文件
*/
public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{
final String BOUNDARY = "---------------------------7da2137580612"; //數據分隔線
final String endline = "--" + BOUNDARY + "--\r\n";//數據結束標志
int fileDataLength = 0;
for(FormFile uploadFile : files){//得到文件類型數據的總長度
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if(uploadFile.getInStream()!=null){
fileDataLength += uploadFile.getFile().length();
}else{
fileDataLength += uploadFile.getData().length;
}
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {//構造文本類型參數的實體數據
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
//計算傳輸給伺服器的實體數據總長度
int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
URL url = new URL(path);
int port = url.getPort()==-1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
OutputStream outStream = socket.getOutputStream();
//下面完成HTTP請求頭的發送
String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: "+ dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
outStream.write(host.getBytes());
//寫完HTTP請求頭後根據HTTP協議再寫一個回車換行
outStream.write("\r\n".getBytes());
//把所有文本類型的實體數據發送出來
outStream.write(textEntity.toString().getBytes());
//把所有文件類型的實體數據發送出來
for(FormFile uploadFile : files){
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
if(uploadFile.getInStream()!=null){
byte[] buffer = new byte[1024];
int len = 0;
while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
outStream.write(buffer, 0, len);
}
uploadFile.getInStream().close();
}else{
outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
//下面發送數據結束標志,表示數據已經結束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(reader.readLine().indexOf("200")==-1){//讀取web伺服器返回的數據,判斷請求碼是否為200,如果不是200,代表請求失敗
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
/**
*單文件上傳
* 提交數據到伺服器
* @param path 上傳路徑(註:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080這樣的路徑測試)
* @param params 請求參數 key為參數名,value為參數值
* @param file 上傳文件
*/
public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{
return post(path, params, new FormFile[]{file});
}
}
⑥ 安卓上傳圖片代碼,c#伺服器端接收代碼,在線等,急。。。
varstr=Requst.InputStream;
StreamReadersr=newStreamReader(str);
varb=sr.ReadToEnd();
File.WriteAllBytes("文件路徑",b);
⑦ android 上傳圖片或文件都是怎麼弄的
一:可以使用httppost上傳文件
二:或者socket寫入文件
上面兩種都可以獲得二進制流,然後把文件寫入流,這一類網路操作最好使用非同步任務模型
⑧ Android 使用OkhttpUtils上傳圖片
IMAGE_FILE_NAME這個確定是文件路徑么?
那個其他我看不出來,我上傳圖片用的都是Xutils,你可以搜搜試試。
⑨ 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 上傳圖片到伺服器
http://192.168.1.212:8011/pd/upload/fileUpload.do;
這個是伺服器地址,你圖片要上傳的地方。。
理論上是需要一個伺服器接收你上傳的圖片的!
他這個demo中的url是本地的,目測是寫demo的人自己寫的用來測試的地址