我们经常会遇到要上传多个文件或者多张图片,例如我们要发一个微信动态,我们可以发送多张带文字的图片,如下图,但是我们是怎么实现这个功能的呢?
1、android上传多张图片。我这里选择使用开源的框架-android-async-http,android-async-http是一个异步加载的http访问框架,超级方便,如果用它来上传文件就更加简单了,几行代码就搞定上传文件的功能。
可以在 android studio里面输入框架。我这里的版本是1.4.9,如果有更新的话,可以使用最新的。
compile 'com.loo;,然后再需要上传多图片的页面写上如下的代码就可以发送图片了,注意:我的服务器是使用struts2开发的,里面接受图片的是用list<file> image来批量接受图片数组的,所以我这里是同样要上传到image的数组,iOS也是这样。
public static void uploadimg(String Uid,File image1,File image2,
AsyncHttpResponseHandler handler) throws FileNotFoundException {
RequestParams params = new RequestParams();
("authorid", Uid);
;
File files[] =new File[2];
files[0]=image1;
files[1]=image2;
String url = ";;
("image",files);
//("image",files,"image/png","");
AsyncHttpClient client=new AsyncHttpClient();
client.post(url, params, handler);
}
调用的时候,只是输入
uploadimg(String Uid,File image1,File image2,
new AsyncHttpResponseHandler...)就可以了。
2、IOS上传多张图片,在ios网络传输,我喜欢用afnetwork这个框架,有很多的大公司也在使用,
比较好用,是一个优秀的框架。它的官方网站是
,由于我是用afnetwork 2.0,所以在新版3.0上传的
有点不一样,不过都是利用了<AFMultipartFormData> formData来传入多个文件。
以下是2.0的上传多张图片的代码:
#pragma mark - 上传图片
- (void)uploadimg
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
、
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
MBProgressHUD * HUD = [[MBProgressHUD alloc] initWithView:];
[ addSubview:HUD];
[HUD show:YES];
[HUD showText:@"发表中..." atMode:MBProgressHUDModeIndeterminate];
NSDictionary *parameters = @{@"uid": };
// formData是遵守了AFMultipartFormData的对象
[manager POST:"192.168.0.125:8080/test/api/v1/uploadimage" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (int i=0; i<; i++) {
UIImageView *imagePathm=[ objectAtIndex:i];
NSData *eachImgData = UIImageJPEGRepresentation(imagePathm.image, 0.5);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
= @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@%d.png", str,i];
NSLog(fileName);
[formData appendPartWithFileData:eachImgData name:@"image" fileName:fileName mimeType:@"image/png"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
[HUD hide:YES];
NSLog(@"完成 %@ ,,", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"错误 %@", error.localizedDescription);
[HUD hide:YES];
}];
}
使用3.0上传多文件的代码
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"; parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"; mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgre];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
}
else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
3、我服务器接收多文件的代码也很简单,部分代码如下。
private List<File> image; // 上传的文件
private List<String> imageFileName; // 文件名称
private List<String> imageContentType; // 文件类型
private String savePath;
public List<File> getImage() {
return image;
}
public void setImage(List<File> image) {
this.image = image;
}
public List<String> getImageFileName() {
returnimageFileName;
}
public void setImageFileName(List<String> imageFileName) {
this.imageFileName = imageFileName;
}
public List<String> getImageContentType() {
returnimageContentType;
}
public void setImageContentType(List<String> imageContentType) {
this.imageContentType = imageContentType;
}
然后再处理方法对文件操作
public void init() throws IOException {
("text/html;charset=utf-8");
("UTF-8");
// 取得需要上传的文件数组
List<File> files = getImage();
if (files != null && () > 0) {
String avatarnameString;
for (int i = 0; i < (); i++) {
FileOutputStream fos;
try {
Map<String, Object> picmap = new HashMap<String, Object>();
String imagenameString=getImageFileName().get(i);
avatarnameString="yeehot_"+getTimeRandName(imagenameString);
fos = new FileOutputStream()+U()+ avatarnameString);
("imgaurl",U()+ avatarnameString);
FileInputStream fis = new FileInputStream(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = (buffer)) > 0) {
(buffer, 0, len);
}
(picmap);
();
();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
使用框架上传文件就是那么的简单,有时我们学会如何快速的实现我们想要的功能,并不是一味的盲目解决问题,利用好现有的资源。