AFNetworking 3.0携带参数上传文件Demo


一、服务端代码:

服务端是java用国产nutz搞的,实际mvc框架都大同小异,就是提交文件的同时还带了个表单参数

	@AdaptBy(type=UploadAdaptor.class, args={"${app.root}/WEB-INF/tmp/user_avatar", "8192", "utf-8", "20000", "102400"})
	@At
	@Aop("redis")
	public Object uploadAvatar(@Param("file")TempFile tf, @Param("token") String token, AdaptorErrorContext err) {
		
		// token 对应客户端参数名
		NutMap re = new NutMap();
		if (err != null && err.getAdaptorErr() != null) {
			return re.setv("code", 3).setv("msg", "文件大小不符合规定");
		}
		if (tf == null) {
			return re.setv("code", 4).setv("msg", "空文件");
		}
		
		if (Strings.isBlank(token)) {
			return re.setv("code", 2).setv("msg", "");// 没有token
		}
		String member_id = jedis().get(token);// 从redis根据token获取member_id
		if (Strings.isBlank(member_id)) {
			return re.setv("code", 2).setv("msg", "");// 未登录
		}
		File f = tf.getFile(); // 这个是保存的临时文件
		FieldMeta meta = tf.getMeta(); // 这个原本的文件信息
		String oldName = meta.getFileLocalName(); // 这个时原本的文件名称

		PropertiesProxy property = new PropertiesProxy("/custom/my.properties");

		String filename = System.currentTimeMillis() + oldName.substring(oldName.lastIndexOf("."));
		StringBuffer sb =new StringBuffer(property.get("my.filepath"));
		sb.append("\\avator\\");
		sb.append(filename);
		
		StringBuffer sbdb =new StringBuffer("/avator/");
		sbdb.append(filename);

		try {
			Files.move(f, new File(sb.toString()));
			//更新数据库
			dao.update(Member.class,Chain.make("avator", sbdb.toString()),Cnd.where("member_id", "=", member_id));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return re.setv("code", 1);
		}

		return re.setv("code", 0).setv("msg", "");
	}


二、客户端代码:

用html表单提交的话,一般是这样的

		<form action="${base}/usr/uploadAvatar" method="post"
			enctype="multipart/form-data">
			头像文件 <input type="file" name="file">
			<p />
			<div>
				token:<input name="token" >
			</div>
			<p />
			<button type="submit">更新头像</button>
		</form>


IOS搞的话,这边用的是AFNetworking 3.0,所以是这样写的

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"图片选中");
    //截取图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.001);
    self.mv.portraitImageView.image = image;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
    // 参数
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"token"] = "param....";
	// 访问路径
    NSString *stringURL = [NSString stringWithFormat:@"%@%@",HOSTURL,kUploadAvatar];
    
    [manager POST:stringURL parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 上传文件
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"上传成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上传错误");
    }];
}


转载请注明:http://blog.csdn.net/wangqiuyun/article/details/50220465



你可能感兴趣的:(java,上传文件,AFNetworking)