3.通过AFN上传多张图片,利用我们自己搭的restful服务

1.服务器端

在com.jlu.api.resource目录下创建FileResource.class文件
并在类里加入以下方法

/**
     * 文件上传
     * 
     * @param fileInputStream
     * @param contentDispositionHeader
     * @return
     * @throws IOException 
     */
    @Context
    ServletContext servletContext;
    @POST
    @Path("upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public Response uploadFile(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition 
            contentDispositionHeader) 
                    throws IOException {
        String fileName = contentDispositionHeader.getFileName();
        //resource为自己创建的目录,
        String rootPath = this.servletContext.getRealPath("/resource" + "/" + fileName);
        File file = new File(rootPath); 
        File parent = file.getParentFile(); 
        //判断目录是否存在,不在创建 
        if(!parent.exists()){ 
            parent.mkdirs(); 
        } 
        file.createNewFile(); 

        OutputStream outpuStream = new FileOutputStream(file);
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileInputStream.read(bytes)) != -1) {
            outpuStream.write(bytes, 0, read);
        }

        outpuStream.flush();
        outpuStream.close();

        fileInputStream.close();

        return Response.status(Response.Status.OK)
                .entity("Upload Success!").build();
    }

2.客户端

- (void)uploadImageByAFN
{
    _imageDataArray = [NSMutableArray array];
    [_imageDataArray addObject:UIImageJPEGRepresentation(_imageView1.image, 1.0)];
    [_imageDataArray addObject:UIImageJPEGRepresentation(imageView2.image, 1.0)];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    int i = 1;
    for (NSData *fileData in _imageDataArray) {
        ++i;
        [mgr POST:@"http://localhost/api/files/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

            [formData appendPartWithFileData:fileData name:@"file" fileName:[NSString stringWithFormat:@"%d.jpg",i] mimeType:@"image/jpg"];

        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            NSLog(@"%@",responseObject);

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            if (error) {
                NSLog(@"%@",error);
            }
        }];
    }

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值