導航:首頁 > 源碼編譯 > android上傳圖片源碼

android上傳圖片源碼

發布時間:2022-01-12 00:15:34

① 求助一個android 文件選擇器的源碼(用於上傳文件時選擇並...

打開文件選擇器:
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
選擇結果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String path = FileUtils.getPath(this, uri);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
FileUtils文件

public class FileUtils {
public static String getPath(Context context, Uri uri) {

if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;

try {
cursor = context.getContentResolver().query(uri, projection,null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}

else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}

return null;
}
}

② 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();
}

}

③ 在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 客戶端通過HTTP BODY發送過來的圖片和文字源代碼

和一般的網頁上傳一樣的。

if(this.FileUpload1.HasFile)
{
int i=this.FileUpload1.PostedFile.ContentLength; //得到上傳文件大小
if(this.FileUpload1.PostedFile.ContentLength>10485760) //1024*1024*10=10M,控制大小
{
Response.Write("<script>alert('文件不能超過10M !')</script>");
return;
}
string fileName=this.FileUpload1.FileName;
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("~/")+"\\File\\"+fileName);//把文件上傳到根目錄的File文件夾

}

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

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

⑥ 求android上傳圖片源代碼,我要做一個相機功能,然後拍完照把相片上傳到伺服器。

您是把照片上傳到哪?如果是微博或者QQ,建議把不能上穿照片的軟體卸載,2.2的不行。 和ROM 和相機有關系~!換一個相機試試 就好了~!我

⑦ android開發怎麼實現拍照上傳

這個其實是一個很泛的問題

我大致說下我的思路:

  1. 用startactivityforresult方法調用系統的攝像頭,隨便拍張照片,把照片保存在某一目錄下面

  2. 點擊完成後,會在onactivityresult中,根據目錄的地址,再把這目錄下面的資源得轉換為文件,接著通過介面進行提交。提交成功後,後台返回一個URL。

  3. 通過這個URL,運用imageload(第三方插件)顯示圖片

⑧ 安卓開發 上傳參數和圖片 現在只寫了上傳圖片,求在代碼中加入上傳參數的代碼~~謝謝~~~(在線等~~)

確實有很多錯誤,1. urlcon請求並沒有執行,2,不說了。。。。 建議網路找例子看看就知道了。 要添加參數需要伺服器配合處理才行。。。

⑨ android 怎麼寫上傳圖片代碼

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

⑩ Android FTP上傳圖片代碼

android客戶端實現FTP文件需要用到 commons-net-3.0.1.jar


  1. 先將jar包復制到android libs目錄下

  2. 復制以下實現代碼

以下為實現代碼:

	/**
*通過ftp上傳文件
*@paramurlftp伺服器地址如:
*@paramport埠如:
*@paramusername登錄名
*@parampassword密碼
*@paramremotePath上到ftp伺服器的磁碟路徑
*@paramfileNamePath要上傳的文件路徑
*@paramfileName要上傳的文件名
*@return
*/
publicStringftpUpload(Stringurl,Stringport,Stringusername,Stringpassword,StringremotePath,StringfileNamePath,StringfileName){
FTPClientftpClient=newFTPClient();
FileInputStreamfis=null;
StringreturnMessage="0";
try{
ftpClient.connect(url,Integer.parseInt(port));
booleanloginResult=ftpClient.login(username,password);
intreturnCode=ftpClient.getReplyCode();
if(loginResult&&FTPReply.isPositiveCompletion(returnCode)){//如果登錄成功
ftpClient.makeDirectory(remotePath);
//設置上傳目錄
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.enterLocalPassiveMode();
fis=newFileInputStream(fileNamePath+fileName);
ftpClient.storeFile(fileName,fis);

returnMessage="1";//上傳成功
}else{//如果登錄失敗
returnMessage="0";
}


}catch(IOExceptione){
e.printStackTrace();
thrownewRuntimeException("FTP客戶端出錯!",e);
}finally{
//IOUtils.closeQuietly(fis);
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
thrownewRuntimeException("關閉FTP連接發生異常!",e);
}
}
returnreturnMessage;
}
閱讀全文

與android上傳圖片源碼相關的資料

熱點內容
求知課堂python2020 瀏覽:260
kafka刪除topic命令 瀏覽:759
phpsql單引號 瀏覽:86
英雄聯盟壓縮壁紙 瀏覽:452
辦公app需要什麼伺服器 瀏覽:628
安卓伺服器怎麼獲得 瀏覽:808
空調壓縮機冷媒的作用 瀏覽:781
淘寶app是以什麼為利的 瀏覽:657
java提取圖片文字 瀏覽:924
我的世界手機版指令復制命令 瀏覽:35
java判斷字元串為數字 瀏覽:926
androidrpc框架 瀏覽:490
雲伺服器essd和ssd 瀏覽:524
家用網關的加密方式 瀏覽:3
怎麼從ppt導出pdf文件 瀏覽:973
換汽車空調壓縮機軸承 瀏覽:845
平板怎麼登錄安卓端 瀏覽:197
圖像拼接計演算法 瀏覽:257
怎麼打開飢荒伺服器的本地文件夾 瀏覽:293
usb掃描槍編程 瀏覽:675