導航:首頁 > 操作系統 > androidform表單上傳圖片

androidform表單上傳圖片

發布時間:2022-05-24 10:44:25

⑴ form 表單上傳圖片,怎樣獲取圖片的全路徑

上傳一成功的一瞬間是放到系統臨時目錄下的,你要通過move_uploaded_file來移動到有效目錄內,如果要操作臨時上傳目錄 ,上傳時通過var_mp($_FILE)能看到的。不過意義不大哈。

android從前台傳圖片文件到後台Servlet,報錯。但是後台通過JSP直接傳文件是可以傳成功。

只是數據從前台傳到後台的話,寫個form表單,post提交,後台servlet接收就好了,也可以jsp接收數據,很多方法。

⑶ android的自帶的httpClient 怎麼上傳文件

Android上傳文件到服務端可以使用HttpConnection 上傳文件,也可以使用Android封裝好的HttpClient類。當僅僅上傳文件可以直接使用httpconnection 上傳比較方便快捷。

1、使用HttpConection上傳文件。將文件轉換成表單數據流。主要的思路就自己構造個http協議內容,服務端解析報文獲得表單數據。代碼片段:

[java] view plain
HttpURLConnection con;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(C_TimeOut);
/* 允許Input、Output,不使用Cache */
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("Content-Type","multipart/form-data;boundary=" + boundary);

/* 設置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
FileInputStream fStream = new FileInputStream(file);

/* 設置每次寫入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];

int length = -1;
/* 從文件讀取數據至緩沖區 */
while((length = fStream.read(buffer)) != -1)
{
/* 將資料寫入DataOutputStream中 */
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
ds.close();

可以參考

①《在 Android 上通過模擬 HTTP multipart/form-data 請求協議信息實現圖片上傳》 (http://bertlee.iteye.com/blog/1134576)。

②《關於android Http訪問,上傳,用了三個方法 》

2、使用Android HttpClient類上傳參數。下面我在網上搜到得代碼,忘記出處了

[java] view plain
private static boolean sendPOSTRequestHttpClient(String path,
Map<String, String> params) throws Exception {
// 封裝請求參數
List<NameValuePair> pair = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 把請求參數變成請求體部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost對象設置發送的URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(uee);
// 創建一個瀏覽器對象,以把POST對象向伺服器發送,並返回響應消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
Log.i("http", "httpclient");
return true;
}
return false;
}

3、使用httpClient上傳文字信息和文件信息。使用httpClient上傳文件非常的方便。不過需要導入apache-mime4j-0.6.jar 和httpmime-4.0.jar兩個.jar包。

[java] view plain
// 封裝請求參數
MultipartEntity mpEntity = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {

StringBody par = new StringBody(entry.getValue());
mpEntity.addPart(entry.getKey(), par);
}
}
// 圖片
if (!imagepath.equals("")) {
FileBody file = new FileBody(new File(imagepath));
mpEntity.addPart("photo", file);
}
// 使用HttpPost對象設置發送的URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(mpEntity);
// 創建一個瀏覽器對象,以把POST對象向伺服器發送,並返回響應消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);

FileBody類可以把文件封裝到表單中,實現附件的上傳。

關於httpClient上傳文件可以參考鏈接: http://www.eoeandroid.com/forum.php?mod=viewthread&tid=76721&page=1

需要用的的ja下載地址r:http://download.csdn.net/detail/china1988s/3791514

參考:

①《在 Android 上通過模擬 HTTP multipart/form-data 請求協議信息實現圖片上傳》 (http://bertlee.iteye.com/blog/1134576)。

②《關於android Http訪問,上傳,用了三個方法 》

⑷ 用表單上傳圖片應怎麼做啊用PHP

<?php
set_time_limit(0);
define('ROOT',dirname(__FILE__).'/');
if($_POST['submit']){
foreach ($_FILES['upfile']['tmp_name'] as $k=>$v){
!$v || (!file_exists(ROOT.'/upload/'.$_FILES['upfile']['name'][$k]) && @getimagesize($v) && @move_uploaded_file($v,ROOT.'/upload/'.$_FILES['upfile']['name'][$k]) && print ('上傳'.$_FILES['upfile']['name'][$k].'成功<br /><img src="'.$site['url'].'upload/upload/'.$_FILES['upfile']['name'][$k].'" />') )|| print ('上傳'.$_FILES['upfile']['name'][$k].'失敗<br />');
}
}
?>
<html>
<head>
<title>上傳</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;margin-left:20px;}
strong{font-size:12px;}
a:link{color:#0066CC;}
a:hover{color:#FF6600;}
a:visited{color:#003366;}
a:active{color:#9DCC00;}
table.itable{}
td.irows{height:20px;background:url("index.php?i=dots") repeat-x bottom}</style>
<script language="JavaScript">
function adpload() {
document.all.upload.innerHTML = '<input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br /><input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br />'+document.all.upload.innerHTML;
}
</script>
</head>
<body>
<center><form enctype="multipart/form-data" method="post" name="upform">
上傳圖片:按上傳按紐,上傳成功後可以直接粘貼圖片於編輯器中 <br><br>
<a href='#' onClick="adpload()">增加上傳文件</a><br><br>
<input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br>
<input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br>
<div id="upload"></div>
<input type="submit" name="submit" value="上傳" style="width:30;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br><br><br>
<br><br>
<a href="index.php">返回</a><br />
</form>
</center>
</body>
</html>

⑸ android一次上傳多張圖片,我的代碼如下,我希望只訪問一次伺服器,上傳多張圖片,求大神指導!

將所有圖片放在一個數組中,,使用輪詢,將整個數組里的內容全部上傳即可,代碼有點多,我就不寫了,你可以在網上搜到的

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

⑺ Android 使用OkhttpUtils上傳圖片

IMAGE_FILE_NAME這個確定是文件路徑么?
那個其他我看不出來,我上傳圖片用的都是Xutils,你可以搜搜試試。

⑻ form表單上傳圖片,java後台轉換(MultipartHttpServletRequest) request報錯

我也想說「你確定別人可以」?

源碼就知道是不行的,你覺得把HttpServletRequest(父類)強轉為MultipartHttpServletRequest(子類)可以嗎?


你可以直接把文件作為一個參數注入進來。

⑼ 求高手解決form表單上傳圖片攜帶參數中文亂碼問題...在線等

1、request.setCharacterEncoding("ISO8859_1");//處理亂碼問題,未成功
這里的設置未必是這個,看你的前台是啥編碼,中文一般是UTF8 GBK GB2312,你的具體是啥編碼,看你的系統,我們以是UTF-8為例子,這里應該是
request.setCharacterEncoding("UTF-8")
2、下面的表單取的時候,這樣取name = fi.getString("UTF-8")

⑽ android 怎麼用二進制流上傳圖片與音頻文件

QusetionForm qusetionForm = (QusetionForm)form; FormFile imageTopic= qusetionForm.getImageTopic(); String name=imageTopic.getFileName(); String url=(servlet.getServletConfig().getServletContext().getRealPath("\\")+name).replace('\\','/');

閱讀全文

與androidform表單上傳圖片相關的資料

熱點內容
三台伺服器配置IP地址 瀏覽:171
如何用命令方塊連續對話 瀏覽:275
win7linux共享文件夾 瀏覽:302
命令符打開本地服務 瀏覽:597
android應用程序源碼 瀏覽:699
安卓開發工程師簡歷怎麼寫 瀏覽:57
熱水器水量伺服器是什麼意思 瀏覽:115
stk衛星編譯 瀏覽:477
對後台程序員的要求 瀏覽:759
ios大文件夾圖標 瀏覽:624
生的計劃pdf 瀏覽:711
oppoa93加密便簽在哪查找 瀏覽:21
兩個數字的加減乘除運算編程 瀏覽:227
給手機加密碼忘記了怎麼辦 瀏覽:601
單片機運算符 瀏覽:297
移動端微信商城源碼 瀏覽:443
編程貓下一個背景在哪裡 瀏覽:359
javaclasstype 瀏覽:240
樂高編程和樂高課的延伸 瀏覽:357
蘋果手機怎麼切換app美國賬號 瀏覽:865