图片上传,android ios Java服务器整合

好久没写帖子了,写个帖子溜达溜达
先介绍一下,我这个整合的环境,已经开发环境。
(1)服务器是java语言写的,用的是jersey 1.18。现在地址是:https://jersey.java.net/download.html。主页是:https://jersey.java.net/
这个官网里面有详细的文档说明和demo已经想过的信息,支持spring的。
下面是移动端的开发说明:
(2)android端的也是使用的第三放的框架,使用的是android-async-http这个开源的库,下载地址是:https://github.com/loopj/android-async-http.
这个开发者的官网是:http://loopj.com/,下面有好多开源的代码,值得学习。
(3)IOS端的开发使用的是开发库是:AFNETworking这个优秀的开源库。下载学习地址是:https://github.com/AFNetworking/AFNetworking
文档和资料在:http://cocoadocs.org/docsets/AFNetworking/2.0.0/,在其官网有很多好的资料哦,在ios我比较喜欢这个网络开源请求库,当然都有其他的开源库了,每个人都有各自的喜好而已,哈哈

服务器的demo解释说明如下,手下是要搭建问服务,写个helloworld,jersey 我是在Tomcat下运行,
需要的jar包如下,对于android开发者来说,有些相互依赖的包,对我们理解上有一点难,至于我只能一点点根据异常寻找我项目中需要的相互依赖包。
所需要的包截图如下:
 
下面我将上传我所需要的jar包:  lib.zip (3.87 MB, 下载次数: 15) 

继续的是配置我的Web.xml文件如下
其实也没怎么配置就是很简单的一个文件而已
[XML]  查看源文件  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<? xml version = "1.0" encoding = "UTF-8" ?>
< web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
  xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee [url]http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd[/url]"
  id = "WebApp_ID" version = "2.5" >
   < display-name >PicData</ display-name >
   < welcome-file-list >
     < welcome-file >index.html</ welcome-file >
   </ welcome-file-list >
   
   < servlet >
     < servlet-name >Jersey REST Service</ servlet-name >
     < servlet-class >com.sun.jersey.spi.container.servlet.ServletContainer</ servlet-class >
     < init-param >
       < param-name >com.sun.jersey.config.property.packages</ param-name >
       < param-value >sample.hello.resources</ param-value >
     </ init-param >
     < load-on-startup >1</ load-on-startup >
   </ servlet >
   
   < servlet-mapping >
     < servlet-name >Jersey REST Service</ servlet-name >
     < url-pattern >/rest/*</ url-pattern >
   </ servlet-mapping >
   
</ web-app >


下面将要写的是一个单独上传图片的接口:
[AppleScript]  查看源文件  复制代码
@POST
	@Path("uploadFile")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces(MediaType.APPLICATION_JSON)
	public Fuck uploadFile(@FormDataParam("file") InputStream file,
	@FormDataParam("fileName") String fileName) {
		// String fileFullName = fileDisposition.getFileName();
		if(file==null)
		{
			Fuck fuck = new Fuck();
			fuck.setAb("传入的图片为null");
			fuck.setB(-1);
			return fuck;
		}
		
		try {
			File path = new File("D:/upload");
			File filep = new File(path, fileName);
			if (!filep.exists()) {
				filep.createNewFile();
			}
			OutputStream outputStream = new FileOutputStream(filep);
			// "D:\\upload", fileName
			// + fileFullName.substring(fileFullName.indexOf("."),
			// fileFullName.length())));
			int length = 0;

			byte[] buff = new byte[256];

			while (-1 != (length = file.read(buff))) {
				outputStream.write(buff, 0, length);
			}
			file.close();
			outputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Fuck fuck = new Fuck();
		return fuck;
	}


批量上图片有个问题是,不知道具体要上传几张图片的呢,所以写法和上述很多有很大差异
代码如下:
[Java]  查看源文件  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@POST
     @Path ( "addNewTopic" )
     @Consumes (MediaType.MULTIPART_FORM_DATA)
     public Fuck addNewTopic( @FormDataParam ( "apiKey" ) String apiKey,
             @FormDataParam ( "text" ) String text,
             @FormDataParam ( "subject" ) String subject, FormDataMultiPart form) {
//form 是所有的图片流,我们要从这里面取到每一张的图片,然后保存,
// text subject apiKey 都是字段,这样我们就可以图片和一些数据一起上传,提交到数据中心去
         System.out.println( "多图片上传" );
         List<BodyPart> bp=    form.getBodyParts();
         for (BodyPart bodyPart : bp) {
             MediaType ty=bodyPart.getMediaType(); //因为用http上传东西,默认是String类型,这里是我们根据http协议定义类型取图片
             if (( "octet-stream" ).equals(ty.getSubtype())) //要筛选规定的图片流,然后保存。
             {
                 System.out.println( "bodyPart: " +bodyPart.getContentDisposition().getFileName());
                 InputStream is =bodyPart.getEntityAs(InputStream. class );
//              File path = new File("D:/upload");
                 String fileLocation = System.currentTimeMillis()+bodyPart.getContentDisposition().getFileName();
                 writeToFile(is, fileLocation); //这个地方,一般用ftp上传到图片服务器,然后将路径写到我们的数据库中...
             }
             
         } Fuck fuck = new Fuck();
return fuck;}


上面的核心代码就是这样的,也是服务器的代码,可以借鉴一下。


下面是android的上传代码,(一定要服务器部署好了,才能上传,别瞎整)
[Java]  查看源文件  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void Updata(View view) {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params= new RequestParams();
        params.put( "fileName" , mName);
        try {
            params.put( "file" , files.get( 0 ));  //这里的file是java类中的File类型
        } catch (Exception e) {
            e.printStackTrace();
        }
        client.post( this , url, params, new TextHttpResponseHandler() {
            
            @Override
            public void onSuccess( int statusCode, Header[] headers, String responseString) {
                Log.e( "Tag" , "请求:_ : onSuccess : " +responseString);
            }
            
            @Override
            public void onFailure( int statusCode, Header[] headers, String responseString,
                    Throwable throwable) {
                Log.e( "Tag" , "请求:_ : onFailure : " +throwable.getMessage());
            }
        });
    }


批量上传如下:
[Java]  查看源文件  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public void MulitePicUp(View view) {
         AsyncHttpClient client = new AsyncHttpClient();
         RequestParams params= new RequestParams();
         params.put( "fileName" , mName);
         params.put( "apiKey" , "apiKey" );
         params.put( "text" , "text" );
         params.put( "subject" , "subject" );
         try {
//            params.put("file", files.get(0));
             if (files.size()> 0 )
             {
                 for ( int i = 0 ; i < files.size(); i++) {
                     params.put( "file: " +i, files.get(i)); //这里put File的时候,字段名字可以随意命名,但是put的字段名字不能一样,因为最后一个put的会覆盖掉前面的
//这里的put有点类Set集合。
                 }
            
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         String url= "http://192.168.0.146:8080/PicData/rest/hello/addNewTopic" ;
         client.post( this , url, params, new TextHttpResponseHandler() {
             @Override
             public void onSuccess( int statusCode, Header[] headers, String responseString) {
                 Log.e( "Tag" , "请求:_ : onSuccess : " +responseString);
             }
             
             @Override
             public void onFailure( int statusCode, Header[] headers, String responseString,
                     Throwable throwable) {
                 Log.e( "Tag" , "请求:_ : onFailure : " +throwable.getMessage());
             }
         });
     }


上面的file是因为我比较懒,写的一个集合List<File> files=new ArrayList<File>();

下面是IOS代码的上传图片;
单张上传:
[Objective-C]  查看源文件  复制代码
NSData *imageData = UIImagePNGRepresentation(image);
    NSString *URL = @"http://192.168.0.146:8080/PicData/rest/hello/uploadFile";
    NSMutableURLRequest *request =[[AFHTTPRequestSerializer serializer]
                                   multipartFormRequestWithMethod:@"POST"
                                   URLString:URL
                                   parameters:@{@"fileName":[NSString stringWithFormat:@"%@.png",[UserBean getUserId]]}
                                   constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                   {
                                       [formData appendPartWithFileData:imageData
                                                                   name:@"file"
                                                               fileName:@"fileName"
                                                               mimeType:@"image/png"];
                                   }];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        }
        else {
            NSLog(@"%@", responseObject);
            //    [UserBean setHeadUrl:savedImagePath];
            //    [self.tableView reloadData];
        }
    }];
    [uploadTask resume];


批量上传如下:
[Objective-C]  查看源文件  复制代码
NSString *URL = @"http://192.168.0.146:8080/PicData/rest/hello/addNewTopic";
    NSMutableURLRequest *request =[[AFHTTPRequestSerializer serializer]
                                   multipartFormRequestWithMethod:@"POST"
                                   URLString:URL
                                   parameters:@{@"fileName":[NSString stringWithFormat:@"%@.png",[UserBean getUserId]]}
                                   constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                   {
                                       for (int i=0; i<pictureArr.count; i++) {  //这里的for循环,字段名字也是可以随意的,
                                           NSData *imageData = UIImagePNGRepresentation(pictureArr[i]);
                                           NSString *name=[NSString stringWithFormat:@"file%d",i];
                                           NSString *fileName=[NSString stringWithFormat:@"fileName%d.png",i];
                                           [formData appendPartWithFileData:imageData
                                                                       name:name
                                                                   fileName:fileName
                                                                   mimeType:@"application/octet-stream"];//主要的是这个mimeType类型设置,为什么呢,最后我再来表述一下,android会设置默认的也是这个类型,ios只能手写了

                                       }
                                      
                                   }];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        }
        else {
            NSLog(@"%@", responseObject);
        }
    }];
    [uploadTask resume];


刚才说的是“application/octet-stream”,其本质就是一个Http content一个协议,属于Http协议,对照表如下:http://tool.oschina.net/commons




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值