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  _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);
            }
        }];
    }

}

你可能感兴趣的:(ios)