導航:首頁 > 操作系統 > android圖片上傳源碼

android圖片上傳源碼

發布時間:2022-10-01 17:59:23

1. 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);

2. android里的圖片怎樣上傳到伺服器並返回顯示在手機上求具體的代碼急用!!!

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

3. android 怎麼寫上傳圖片代碼

請問圖片是放在android手機的哪個地方,要在android手機怎麼顯示返回呢,主類中有個按鈕來添加圖片,還有一個按鈕是用來上傳圖片,然後寫個監聽,

4. 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});
}
}

5. android圖片上傳的問題

Intent intent = new Intent();

intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);

然後在重寫activity裡面的onActivityResult方法,獲取到你選擇的圖片的uri,uri=data.getData();

你可以試下,我是這樣實現的!

6. 怎樣在android系統中上傳圖片,信息。以及修改信息,這些代碼

我一般都是通過遍歷集合的方式來上傳圖片。而且一般都不會去管這個上傳的順序,只需要服務端按你需要返回數據就可以了

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

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

8. android 如何使用HTTP上傳圖片到伺服器指定路勁下,求源碼 郵箱 [email protected]

安卓有專門的ftp應用啊
你去找一個 就可以了啊
和一般的ftp軟體一樣的啊
額 HTTP啊 看錯了
那就不知道了 不知道一般的網站的上傳代碼 可不可以用

9. android上傳圖片到伺服器,求伺服器那邊和android的Activity的完整代碼。

伺服器端servlet代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//獲取輸入流,是HTTP協議中的實體內容
ServletInputStream sis=request.getInputStream();

File file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+0+".jpg");
for (int imgnum = 0;file.exists();imgnum++)
{
file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+imgnum+".jpg");
}
//緩沖區
byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream(file);
int len=sis.read(buffer, 0, 1024);
//把流里的信息循環讀入到文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}

android客戶端代碼:
public static void uploadFile(String imageFilePath)
{
String actionUrl = "http://192.168.1.32:8080/UploadServer/ImageServlet";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();

con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.setRequestMethod("POST");

DataOutputStream ds = new DataOutputStream(con.getOutputStream());
File file = new File(imageFilePath);

FileInputStream fStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];

int length = -1;

while((length = fStream.read(buffer)) != -1)
{

ds.write(buffer, 0, length);
}

fStream.close();
ds.flush();

InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}

ds.close();
}
catch(Exception e)
{
e.printStackTrace();
}

}

10. 在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圖片上傳源碼相關的資料

熱點內容
五菱宏光空調壓縮機 瀏覽:64
為什麼app佔用幾百兆 瀏覽:676
自動解壓失敗叫我聯系客服 瀏覽:482
易語言新手源碼 瀏覽:456
oa伺服器必須有固定ip地址 瀏覽:42
傳奇源碼分析是什麼 瀏覽:267
解放壓縮機支架 瀏覽:255
程序員禿頂搞笑相遇 瀏覽:6
IBM手機app商店叫什麼名字 瀏覽:834
jpeg壓縮質量 瀏覽:774
雲伺服器評測對比 瀏覽:145
java日期轉string 瀏覽:221
openfire源碼編譯 瀏覽:897
在線小工具箱引流網站源碼 瀏覽:337
非科班程序員自學 瀏覽:801
壓縮泡沫鞋底底材 瀏覽:220
程序員職場第一課2正確的溝通 瀏覽:680
遇到不合法app應該怎麼辦 瀏覽:92
匯編程序編譯後的文件 瀏覽:81
大智慧均線源碼 瀏覽:374