导航:首页 > 源码编译 > 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命令 浏览:757
phpsql单引号 浏览:84
英雄联盟压缩壁纸 浏览:450
办公app需要什么服务器 浏览:626
安卓服务器怎么获得 浏览:806
空调压缩机冷媒的作用 浏览:779
淘宝app是以什么为利的 浏览:655
java提取图片文字 浏览:922
我的世界手机版指令复制命令 浏览:33
java判断字符串为数字 浏览:924
androidrpc框架 浏览:488
云服务器essd和ssd 浏览:522
家用网关的加密方式 浏览:1
怎么从ppt导出pdf文件 浏览:971
换汽车空调压缩机轴承 浏览:845
平板怎么登录安卓端 浏览:195
图像拼接计算法 浏览:255
怎么打开饥荒服务器的本地文件夹 浏览:291
usb扫描枪编程 浏览:673