當前位置:首頁 » 安卓系統 » androidsocket上傳文件

androidsocket上傳文件

發布時間: 2023-02-05 07:05:26

① 安卓開發怎麼使用socket從客戶端傳輸bitmap和字元串到伺服器端

你可以把bitmap轉換成byte數組,字元串也轉換成byte數組,都放到同一個byte數組里,用socket發送,記住是第幾個byte開始是bitmap或者字元串,在伺服器在解析出來

② 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#編寫的socket伺服器如何發數據給android手機

以下是android手機上發送文件名並且得到文件大小的代碼Java
code
//
向伺服器提出下載請求,返回下載文件的大小
private
long
request(String
fileName,
String
password)
throws
IOException
{
//
獲取socket的輸入流並包裝成DataInputStream
DataInputStream
in
=
new
DataInputStream(socket.getInputStream());
//
獲取socket的輸出流並包裝成PrintWriter
PrintWriter
out
=
new
PrintWriter(new
OutputStreamWriter(
socket.getOutputStream()));
//
生成下載請求字元串
String
requestString
=
fileName;//
+
@
+
password;
System.out.println(發出下載請求:+fileName);
out.println(requestString);
//
發出下載請求
out.flush();
return
in.readLong();
//
接收並返回下載文件長度}
以下是C#伺服器收到android發來的文件名,知道文件之後發送文件大小和文件的代碼C#
code
private
string
ReceiveFileName(){string
recvStr
=
;byte[]
recvBytes
=
new
byte[1024];int
bytes
=
m_socket.Receive(recvBytes,
recvBytes.Length,
0);
//從android客戶端接受信息recvStr
=
Encoding.ASCII.GetString(recvBytes,
0,
bytes);Console.WriteLine(文件名+recvStr);return
recvStr;//返迴文件名}
private
void
SendFile(){while
(m_IsStart){string
fileName
=
ReceiveFileName();if
(fileName
!=
){if
(File.Exists(m_FileDirect
+
1.jpg))//下載本地存在的一個文件{FileInfo
fi
=
new
FileInfo(m_FileDirect
+
1.jpg);byte[]
len
=
BitConverter.GetBytes(fi.Length);m_socket.Send(len);//發送文件的長度//發送文件try{m_socket.SendFile(m_FileDirect
+
1.jpg);}catch
(Exception
e){Console.WriteLine(出現錯誤
+
e.Message);}}}}}
------解決方案--------------------------------------------------------
Java
code//
獲取socket的輸入流並包裝成DataInputStream
這個不就是接收的地方嗎?在第一段代碼中

④ Android端使用Socket傳輸圖片

好久之前做過個Demo,可以傳照片跟音樂的,可惜沒了哎,要不直接發給你了

⑤ 在Android端使用socket傳輸圖片到java伺服器,求源代碼

/**
*思想:
1.直接將所有數據安裝位元組數組發送
2.對象序列化方式
*/

/**
*thread方式
*
*@authorAdministrator
*/
{
privatestaticfinalintFINISH=0;
privateButtonsend=null;
privateTextViewinfo=null;
privateHandlermyHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseFINISH:
Stringresult=msg.obj.toString();//取出數據
if("true".equals(result)){
TestSocketActivity4.this.info.setText("操作成功!");
}else{
TestSocketActivity4.this.info.setText("操作失敗!");
}
break;
}
}
};


@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
//StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
//StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()
//.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
//.penaltyLog().penaltyDeath().build());

this.send=(Button)super.findViewById(R.id.send);
this.info=(TextView)super.findViewById(R.id.info);
this.send.setOnClickListener(newSendOnClickListener());
}

{
@Override
publicvoidonClick(Viewv){
try{
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
//1:
Socketclient=newSocket("192.168.1.165",9898);
//2:
ObjectOutputStreamoos=newObjectOutputStream(
client.getOutputStream());
//3:
UploadFilemyFile=SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);//寫文件對象
//oos.writeObject(null);//避免EOFException
oos.close();


BufferedReaderbuf=newBufferedReader(
newInputStreamReader(client
.getInputStream()));//讀取返回的數據
Stringstr=buf.readLine();//讀取數據
Messagemsg=TestSocketActivity4.this.myHandler
.obtainMessage(FINISH,str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
client.close();
}catch(Exceptione){
Log.i("UploadFile",e.getMessage());
}
}
}).start();
}catch(Exceptione){
e.printStackTrace();
}
}

()throwsException{//包裝了傳送數據
UploadFilemyFile=newUploadFile();
myFile.setTitle("tangcco安卓之Socket的通信");//設置標題
myFile.setMimeType("image/png");//圖片的類型
Filefile=newFile(Environment.getExternalStorageDirectory()
.toString()
+File.separator
+"Pictures"
+File.separator
+"b.png");
InputStreaminput=null;
try{
input=newFileInputStream(file);//從文件中讀取
ByteArrayOutputStreambos=newByteArrayOutputStream();
bytedata[]=newbyte[1024];
intlen=0;
while((len=input.read(data))!=-1){
bos.write(data,0,len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt("png");
}catch(Exceptione){
throwe;
}finally{
input.close();
}
returnmyFile;
}
}

}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;

publicStringgetTitle(){
returntitle;
}

publicvoidsetTitle(Stringtitle){
this.title=title;
}

publicbyte[]getContentData(){
returncontentData;
}

publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}

publicStringgetMimeType(){
returnmimeType;
}

publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}

publiclonggetContentLength(){
returncontentLength;
}

publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}

publicStringgetExt(){
returnext;
}

publicvoidsetExt(Stringext){
this.ext=ext;
}

}

下邊是服務端

publicclassMain4{
publicstaticvoidmain(String[]args)throwsException{
ServerSocketserver=newServerSocket(9898);//伺服器端埠
System.out.println("服務啟動........................");
booleanflag=true;//定義標記,可以一直死循環
while(flag){//通過標記判斷循環
newThread(newServerThreadUtil(server.accept())).start();//啟動線程
}
server.close();//關閉伺服器
}
}


{
="D:"+File.separator+"myfile"
+File.separator;//目錄路徑
privateSocketclient=null;
privateUploadFileupload=null;

publicServerThreadUtil(Socketclient){
this.client=client;
System.out.println("新的客戶端連接...");
}

@Override
publicvoidrun(){
try{
ObjectInputStreamois=newObjectInputStream(
client.getInputStream());//反序列化
this.upload=(UploadFile)ois.readObject();//讀取對象//UploadFile需要和客戶端傳遞過來的包名類名相同,如果不同則會報異常
System.out.println("文件標題:"+this.upload.getTitle());
System.out.println("文件類型:"+this.upload.getMimeType());
System.out.println("文件大小:"+this.upload.getContentLength());

PrintStreamout=newPrintStream(this.client.getOutputStream());//BufferedWriter
out.print(this.saveFile());//返回響應
// BufferedWriterwriter=null;
// writer.write("");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
this.client.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

privatebooleansaveFile()throwsException{//負責文件內容的保存
/**
*java.util.UUID.randomUUID():
*UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法。UUID(Universally
*UniqueIdentifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
*是由一個十六位的數字組成
*,表現出來的形式。由以下幾部分的組合:當前日期和時間(UUID的第一個部分與時間有關,如果你在生成一個UUID之後,
*過幾秒又生成一個UUID,
*則第一個部分不同,其餘相同),時鍾序列,全局唯一的IEEE機器識別號(如果有網卡,從網卡獲得,沒有網卡以其他方式獲得
*),UUID的唯一缺陷在於生成的結果串會比較長,字元串長度為36。
*
*UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法。UUID(Universally
*UniqueIdentifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
*是由一個十六位的數字組成,表現出來的形式
*/
Filefile=newFile(DIRPATH+UUID.randomUUID()+"."
+this.upload.getExt());
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
OutputStreamoutput=null;
try{
output=newFileOutputStream(file);
output.write(this.upload.getContentData());
returntrue;
}catch(Exceptione){
throwe;
}finally{
output.close();
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;

publicStringgetTitle(){
returntitle;
}

publicvoidsetTitle(Stringtitle){
this.title=title;
}

publicbyte[]getContentData(){
returncontentData;
}

publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}

publicStringgetMimeType(){
returnmimeType;
}

publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}

publiclonggetContentLength(){
returncontentLength;
}

publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}

publicStringgetExt(){
returnext;
}

publicvoidsetExt(Stringext){
this.ext=ext;
}

}

⑥ android 上傳圖片或文件都是怎麼弄的

一:可以使用httppost上傳文件
二:或者socket寫入文件
上面兩種都可以獲得二進制流,然後把文件寫入流,這一類網路操作最好使用非同步任務模型

⑦ android如何通過socket上傳視頻或者音頻先謝過啦

這個實驗我是用兩台pc做的實驗,沒有用真機,用的是emule,總體效果感覺可以
大致的思路是這樣的
socket的通信分兩種一種是 tcp另一種是udp,這個之間的通信方式我就不多說了,
主要的重點是許可權的android.premisson,INTERNET

tcp
new Socket();
......

udp
new DatagramSocket();
......

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

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

⑨ 求教!android報異常FileNotFoundException! 學習android開發編寫SOCKET客戶端,用來發送文件

FileNotFoundException:/f:/words.txt

看清楚異常的提示,它是報的文件「/f:/words.txt」沒有找到,你用的是windows下的文件目錄表示方法,可是android是基於linux平台的,它會到根目錄「/」下找「f:」這個目錄,這肯定找不到了。

解決方法:
1、將words.txt 放到項目的asserts目錄下,然後
InputStream inputStream = SocketClientActivity.this.getAssets().open("words.txt");
2、將words.txt 放到SD卡里,然後
InputStream inputStream = new FileInputStream("/sdcard/words.txt");
3、也可以將你的文件放在你的工程默認路徑下,然後再讀:
FileInputStream fis = context.openFileInput("words.txt");

熱點內容
內置存儲卡可以拆嗎 發布:2025-05-18 04:16:35 瀏覽:333
編譯原理課時設置 發布:2025-05-18 04:13:28 瀏覽:376
linux中進入ip地址伺服器 發布:2025-05-18 04:11:21 瀏覽:610
java用什麼軟體寫 發布:2025-05-18 03:56:19 瀏覽:31
linux配置vim編譯c 發布:2025-05-18 03:55:07 瀏覽:107
砸百鬼腳本 發布:2025-05-18 03:53:34 瀏覽:941
安卓手機如何拍視頻和蘋果一樣 發布:2025-05-18 03:40:47 瀏覽:739
為什麼安卓手機連不上蘋果7熱點 發布:2025-05-18 03:40:13 瀏覽:802
網卡訪問 發布:2025-05-18 03:35:04 瀏覽:510
接收和發送伺服器地址 發布:2025-05-18 03:33:48 瀏覽:371