ios端与服务器端之间图片传输实例

2017-08-12 20:15:28来源:CSDN作者:dearKundy人点击

分享

程序实现的功能:在客户端选择照片上传到服务器,在服务器端接收图片存储到数据库。服务器根据ID返回图片到客户端,在客户端接收图片。

客户端:Objective-C

服务器:Java


1.在客户端上传照片到服务器,利用AFNetworking的多表单传输。关键代码如下:

//上传头像图片到服务器-(void) postImageToServer{    _manager = [AFHTTPSessionManager manager] ;    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:                                                          @"application/json",                                                          @"text/html"       ,                                                          @"image/jpeg"      ,                                                          @"image/png"       ,                                                          @"image/jpg"       ,                                                          @"application/octet-stream",                                                          @"text/json"      ,                                                          nil] ;        _manager.requestSerializer  = [AFHTTPRequestSerializer serializer ] ;    _manager.responseSerializer = [AFHTTPResponseSerializer serializer] ;        [_manager POST:@"http://192.168.31.244:8080/ImageUploadServer/uploadimage"        parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)     {         //上传学生学号到服务器         //_strStudentId为学生学号字符串         NSData *data = [_strStudentId dataUsingEncoding:NSUTF8StringEncoding] ;         [formData appendPartWithFormData:data name:@"studentId"] ;                  //在网络开发中,上传文件时,文件是不允许被覆盖,文件重名         //要解决此问题,可以在上传时使用当前的系统事件作为文件名         NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;                  //设置时间格式         formatter.dateFormat = @"yyyyMMddHHmmss" ;         NSString *str = [formatter stringFromDate:[NSDate date]] ;         NSString *fileName = [NSString stringWithFormat:@"%@.jpeg",str] ;                  //压缩图片         //_imageEdit是从相机获取的图片         NSData *imageData = UIImageJPEGRepresentation(_imageEdit, 0.1) ;                  //上传图片到服务器         [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"] ;     }          //上传过程中调用          progress:^(NSProgress * _Nonnull uploadProgress)     {     }          //上传成功调用           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)     {         NSLog(@"上传成功!") ;     }           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)    {        NSLog(@"上传失败") ;     }] ;}

2.在服务器端接收图片保存到服务器本地,servlet的关键代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 	{		try {			//获取客户端传过来图片的二进制流			InputStream stream = request.getInputStream() ;						//以当前时间戳为图片命名			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");			String strCurrentTime = df.format(new Date()) ;			String imagePath = "/Users/kun/Desktop/test/" + strCurrentTime +".jpeg" ;						FileOutputStream fos = new FileOutputStream(imagePath) ;			byte[] bbuf = new byte[32] ;			int hasRead = 0 ;			while((hasRead = stream.read(bbuf)) > 0)			{				fos.write(bbuf, 0, hasRead);//将文件写入服务器的硬盘上			}			fos.close();			stream.close();						/*			 *  但是需要注意,采用这种原始的方式写入文件时,你会发现被写入的文件内容前4行并非是读取文件的真正内容,			 * 从第四行开始才是正文数据。第二行是文件路径以及名称。所以通常的做法是,先将文件写入临时文件中,然后			 * 再采用RandomAccessFile读取临时文件的第四行以后部分。写入到目标文件中。			 */						Byte n ;			//read the temp file			RandomAccessFile random = new RandomAccessFile(imagePath, "r") ;			//read line2 to find the name of the upload file.			int second = 1 ;			String secondLine = null ;			while(second <=2)			{				secondLine = random.readLine();				second++ ;			}			//get the last location of the dir char.'//'			int position = secondLine.lastIndexOf('//') ;			//get the name of the upload file.			String fileName = secondLine.substring(position+1, secondLine.length()-1) ;			//relocate to the head of file			random.seek(0);			//get the location of the char.'Enter' in Line4.			long forthEndPosition = 0 ;			int forth = 1 ;			while((n=random.readByte())!=-1 && (forth <= 4))			{				if(n=='/n')				{					forthEndPosition = random.getFilePointer() ;					forth++ ;				}			}						RandomAccessFile random2 = new RandomAccessFile(imagePath, "rw") ;			//locate the end position of the content.Count backwards 6 lines			random.seek(random.length());			long endPosition = random.getFilePointer() ;			long mark = endPosition ;			int j = 1 ;			while((mark >= 0) && (j <=6))			{				mark-- ;				random.seek(mark);				n=random.readByte() ;				if(n=='/n')				{					endPosition=random.getFilePointer() ;					j++ ;				}			}						//locate to the begin of content.Count for 4 lines's end position.			random.seek(forthEndPosition);			long startPoint = random.getFilePointer() ;			//read the real content and write it to the realFile.			while(startPoint < endPosition-1)			{				n = random.readByte() ;				random2.write(n);				startPoint = random.getFilePointer() ;			}			random.close();			random2.close();		} catch (Exception e) {			e.printStackTrace();		}			}


3.将图片插入到数据库


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台