新聞中心
android中如何上傳圖片到FTP服務(wù)器
android客戶(hù)端實(shí)現(xiàn)FTP文件需要用到 commons-net-3.0.1.jar

創(chuàng)新互聯(lián)是一家專(zhuān)業(yè)提供八宿企業(yè)網(wǎng)站建設(shè),專(zhuān)注與網(wǎng)站建設(shè)、做網(wǎng)站、HTML5、小程序制作等業(yè)務(wù)。10年已為八宿眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專(zhuān)業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。
先將jar包復(fù)制到android libs目錄下
復(fù)制以下實(shí)現(xiàn)代碼
以下為實(shí)現(xiàn)代碼:
/**
* 通過(guò)ftp上傳文件
* @param url ftp服務(wù)器地址 如:
* @param port 端口如 :
* @param username 登錄名
* @param password 密碼
* @param remotePath 上到ftp服務(wù)器的磁盤(pán)路徑
* @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);
// 設(shè)置上傳目錄
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客戶(hù)端出錯(cuò)!", e);
} finally {
//IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("關(guān)閉FTP連接發(fā)生異常!", e);
}
}
return returnMessage;
}
android如何實(shí)現(xiàn)圖片批量上傳??
首先,以下架構(gòu)下的批量文件上傳可能會(huì)失敗或者不會(huì)成功:
1.android客戶(hù)端+springMVC服務(wù)端:服務(wù)端采用org.springframework.web.multipart.MultipartHttpServletRequest作為批量上傳接收類(lèi),這種搭配下的批量文件上傳會(huì)失敗,最終服務(wù)端只會(huì)接受到一個(gè)文件,即只會(huì)接受到第一個(gè)文件??赡芤?yàn)镸ultipartHttpServletRequest對(duì)servlet原本的HttpServletRequest類(lèi)進(jìn)行封裝,導(dǎo)致批量上傳有問(wèn)題。
2.android客戶(hù)端+strutsMVC服務(wù)端:
上傳成功的方案:
采用android客戶(hù)端+Servlet(HttpServletRequest)進(jìn)行文件上傳。
Servlet端代碼如下:
[java] view plaincopyprint?
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("表單參數(shù)名:" + item.getFieldName() + ",表單參數(shù)值:" + item.getString("UTF-8"));
}
else
{
if (item.getName() != null !item.getName().equals(""))
{
System.out.println("上傳文件的大小:" + item.getSize());
System.out.println("上傳文件的類(lèi)型:" + item.getContentType());
// item.getName()返回上傳文件在客戶(hù)端的完整路徑名稱(chēng)
System.out.println("上傳文件的名稱(chēng):" + 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", "沒(méi)有選擇上傳文件!");
}
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
request.setAttribute("upload.message", "上傳文件失?。?);
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
android端代碼如下:
[java] view plaincopyprint?
public class SocketHttpRequester {
/**
*多文件上傳
* 直接通過(guò)HTTP協(xié)議提交數(shù)據(jù)到服務(wù)器,實(shí)現(xiàn)如下面表單提交功能:
* FORM METHOD=POST ACTION="" 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這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用或這樣的路徑測(cè)試)
* @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值
* @param file 上傳文件
*/
public static boolean post(String path, MapString, String params, FormFile[] files) throws Exception{
final String BOUNDARY = "---------------------------7da2137580612"; //數(shù)據(jù)分隔線(xiàn)
final String endline = "--" + BOUNDARY + "--\r\n";//數(shù)據(jù)結(jié)束標(biāo)志
int fileDataLength = 0;
for(FormFile uploadFile : files){//得到文件類(lèi)型數(shù)據(jù)的總長(zhǎng)度
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.EntryString, String entry : params.entrySet()) {//構(gòu)造文本類(lèi)型參數(shù)的實(shí)體數(shù)據(jù)
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");
}
//計(jì)算傳輸給服務(wù)器的實(shí)體數(shù)據(jù)總長(zhǎng)度
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請(qǐng)求頭的發(fā)送
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());
//寫(xiě)完HTTP請(qǐng)求頭后根據(jù)HTTP協(xié)議再寫(xiě)一個(gè)回車(chē)換行
outStream.write("\r\n".getBytes());
//把所有文本類(lèi)型的實(shí)體數(shù)據(jù)發(fā)送出來(lái)
outStream.write(textEntity.toString().getBytes());
//把所有文件類(lèi)型的實(shí)體數(shù)據(jù)發(fā)送出來(lái)
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());
}
//下面發(fā)送數(shù)據(jù)結(jié)束標(biāo)志,表示數(shù)據(jù)已經(jīng)結(jié)束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(reader.readLine().indexOf("200")==-1){//讀取web服務(wù)器返回的數(shù)據(jù),判斷請(qǐng)求碼是否為200,如果不是200,代表請(qǐng)求失敗
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
/**
*單文件上傳
* 提交數(shù)據(jù)到服務(wù)器
* @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用或這樣的路徑測(cè)試)
* @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值
* @param file 上傳文件
*/
public static boolean post(String path, MapString, String params, FormFile file) throws Exception{
return post(path, params, new FormFile[]{file});
}
}
android 客戶(hù)端開(kāi)發(fā) 如何同時(shí)上傳多張照片
1、在微博頁(yè)面點(diǎn)擊左上角發(fā)布按鈕后,點(diǎn)擊“照相機(jī)”標(biāo)識(shí)或“圖片”標(biāo)識(shí);
2、選擇圖片進(jìn)行上傳,選定后點(diǎn)擊右下角的綠色“確認(rèn)”按鈕
3、多圖上傳最多支持9張圖片,如果還需添加可點(diǎn)擊“十”字繼續(xù)選擇上傳,如果添加完畢可點(diǎn)擊右上角的藍(lán)色“發(fā)布”即可。
當(dāng)前文章:android上傳圖片,Android上傳圖片怎么做
轉(zhuǎn)載來(lái)于:http://www.dlmjj.cn/article/dscogsd.html


咨詢(xún)
建站咨詢(xún)
