248,AFNetworking 3的使用(二)
/**
* 例項4:執行下載檔案的方法,可以監控下載進度
*/
@property (weak, nonatomic) IBOutletUIProgressView *progress;
@property (weak, nonatomic) IBOutletUILabel *progressPercent;
/**
* 執行下載檔案的方法,可以監控下載進度
*/
- (void)downloadFiles{
//1,建立url
NSString *url =@"http://192.168.0.103:8080/theaddressbook/videos/01-私人通訊錄01-基本框架搭建
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//2,建立網路管理者
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManagermanager];
//3,利用網路管理者下載資料
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:url]];
/*
destination
- targetPath: 系統給我們自動寫入的檔案路徑
- block的返回值,要求返回一個URL,返回的這個URL就是剪下的位置的路徑
completionHandler
- url :destination返回的URL == block的返回的路徑
*/
/*
@property int64_t totalUnitCount; 需要下載檔案的總大小
@property int64_t completedUnitCount; 當前已經下載的大小
*/
NSURLSessionDownloadTask *downTask = [sessionManagerdownloadTaskWithRequest
NSLog(@"%lld/%lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
dispatch_async(dispatch_get_main_queue(), ^{
self.progress.progress =1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
int precentData = (int)(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount * 100);
NSString *result = [NSStringstringWithFormat:@"%i",precentData];
result = [result stringByAppendingString:@"%"];
self.progressPercent.text = result;
});
} destination:^NSURL *_Nonnull(NSURL *_Nonnull targetPath,NSURLResponse * _Nonnull response) {
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject];
NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
return [NSURLfileURLWithPath:path];
} completionHandler:^(NSURLResponse *_Nonnull response,NSURL * _Nullable filePath,NSError * _Nullable error) {
//此處已經在主執行緒了
NSLog(@"filePath = %@",filePath.absoluteString);
}];
/*
要跟蹤進度,需要使用 NSProgress,是在 iOS 7.0推出的,專門用來跟蹤進度的類!
NSProgress只是一個物件!如何跟蹤進度!-> KVO對屬性變化的監聽!
@property int64_t totalUnitCount; 總單位數
@property int64_t completedUnitCount; 完成單位數
*/
// 4.啟動任務
[downTask resume];
}
/**
* 例項五:上傳檔案
*/
IOS端的程式碼:
- (void)uploadFiles{
//1,建立網路管理者
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManagermanager];
//2,傳遞的引數
NSDictionary *paras = @{@"username":@"ljs"};
//3,formData:專門用於拼接需要上傳的資料
NSString *url = @"http://192.168.0.103:8080/theaddressbook/uploadController/doPost.do";
[sessionManager POST:url parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
/**
* 例子一 上傳照片 ImageTest.png
*/
//NSData *data = [ViewController getImageData];
//[formData appendPartWithFileData:data name:@"file" fileName:@"ImageTest.png" mimeType:@"image/png"];
/**
* 例子二 上傳檔案 fileTest.txt
*/
//NSData *data = [ViewController getFileData];
//[formData appendPartWithFileData:data name:@"file" fileName:@"fileTest.txt" mimeType:@"text/txt"];
/**
* 例子三 上傳檔案 audioTest.mp3
*/
//NSData *data = [ViewController getAudioData];
//[formData appendPartWithFileData:data name:@"file" fileName:@"audioTest.mp3" mimeType:@"audio/mp3"];
/**
* 例子四 上傳檔案 vidioTest.mp4
*/
NSData *data = [ViewController getVidioData];
[formData appendPartWithFileData:data name:@"file"fileName:@"vidioTest.mp4"mimeType:@"video/mp4"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%lld/%lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上傳成功!");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上傳失敗!");
}];
}
//獲取沙盒中Documents的路徑
+(NSString *)documentsPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
//獲得document檔案路徑
+ (NSString *)getFilePath:(NSString *)fileName{
NSString *path = [self documentsPath];
path = [path stringByAppendingPathComponent:fileName];
NSLog(@"路徑為: %@",path);
return path;
}
//判斷檔案是否存在
+ (BOOL)FileIsExists:(NSString*) checkFile{
if([[NSFileManagerdefaultManager]fileExistsAtPath:checkFile])
{
return true;
}
return false;
}
//獲取圖片
+ (NSData *)getImageData{
NSString *imagePath = [self getFilePath:@"imageTest.png"];
NSData *imageData = nil;
if([self FileIsExists:imagePath]){
imageData = [NSData dataWithContentsOfFile:imagePath];
}
return imageData;
}
//獲取檔案
+ (NSData *)getFileData{
NSString *filePath = [self getFilePath:@"fileTest.txt"];
NSData *fileData = nil;
if([self FileIsExists:filePath]){
fileData = [NSData dataWithContentsOfFile:filePath];
}
return fileData;
}
//獲取音訊
+ (NSData *)getAudioData{
NSString *audioPath = [self getFilePath:@"audioTest.mp3"];
NSData *audioData = nil;
if([self FileIsExists:audioPath]){
audioData = [NSData dataWithContentsOfFile:audioPath];
}
return audioData;
}
//獲取視訊
+ (NSData *)getVidioData{
NSString *vidioPath = [self getFilePath:@"audioTest.mp3"];
NSData *vidioData = nil;
if([self FileIsExists:vidioPath]){
vidioData = [NSData dataWithContentsOfFile:vidioPath];
}
return vidioData;
}
/*
備註
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
*/
Java伺服器端的程式碼:package com.ljs.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ljs.service.IUsersContactsOperationImp;
@Controller
@RequestMapping(value = "/uploadController")
public class UploadController {
@Resource
private IUsersContactsOperationImp operationImp;
@SuppressWarnings("deprecation")
@RequestMapping(value = "/doPost.do", method = RequestMethod.POST)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 獲取資料
// 建立一個臨時檔案存放要上傳的檔案,第一個引數為上傳檔案大小,第二個引數為存放的臨時目錄
DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 5,
new File("/Users/JS/Desktop/Images/temp1"));
// 設定緩衝區大小為 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 建立一個檔案上傳的控制代碼
ServletFileUpload upload = new ServletFileUpload(factory);
// 設定上傳檔案的整個大小和上傳的單個檔案大小
upload.setSizeMax(1024 * 1024 * 50);
upload.setFileSizeMax(1024 * 1024 * 5);
// 圖片
String[] ImagesExts = { "jpg", "png" };
// 視訊
String[] videosExts = { "mp4", "avi", "mov" };
// 音訊
String[] audiosExts = { "mp3" };
// 檔案
String[] filesExts = { "txt", "doc", "docx", "plist" };
try { // 把頁面表單中的每一個表單元素解析成一個
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
// 如果是一個普通的表單元素(type不是file的表單元素)
if (fileItem.isFormField()) {
System.out.println("--------普通的表單元素----------");
System.out.println("key = " + fileItem.getFieldName());
// 得到對應表單元素的名字
System.out.println("values = " + fileItem.getString());
// 得到表單元素的值
} else { // 獲取檔案的字尾名
System.out.println("--------視訊,圖片,音訊等檔案 ----------");
String fileFullName = fileItem.getName();// 得到檔案的名字
System.out.println("檔名字 = " + fileFullName);
String fileName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
String fileExt = fileFullName.substring(fileFullName.lastIndexOf(".") + 1, fileFullName.length());
System.out.println("檔案的字尾名 = " + fileExt);
if (judgeFileType(ImagesExts, fileExt)) {
System.out.println("開始儲存照片了!");
try {
// 將檔案上傳到專案的upload目錄並命名
fileItem.write(
new File("/DevelopTool/eclipseworkplace/theaddressbook/WebContent/resources/images/"
+ fileName + "." + fileExt));
} catch (Exception e) {
e.printStackTrace();
}
} else if (judgeFileType(videosExts, fileExt)) {
System.out.println("開始儲存視訊了!");
try {
fileItem.write(
new File("/DevelopTool/eclipseworkplace/theaddressbook/WebContent/resources/videos/"
+ fileName + "." + fileExt));
} catch (Exception e) {
e.printStackTrace();
}
} else if (judgeFileType(audiosExts, fileExt)) {
System.out.println("開始儲存音訊了!");
try {
fileItem.write(
new File("/DevelopTool/eclipseworkplace/theaddressbook/WebContent/resources/audios/"
+ fileName + "." + fileExt));
} catch (Exception e) {
e.printStackTrace();
}
} else if (judgeFileType(filesExts, fileExt)) {
System.out.println("開始儲存檔案了!");
try {
fileItem.write(
new File("/DevelopTool/eclipseworkplace/theaddressbook/WebContent/resources/files/"
+ fileName+ "." + fileExt));
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("該檔案型別不能夠上傳");
}
}
}
} catch (FileUploadBase.SizeLimitExceededException e) {
System.out.println("整個請求的大小超過了規定的大小...");
} catch (FileUploadBase.FileSizeLimitExceededException e) {
System.out.println("請求中一個上傳檔案的大小超過了規定的大小...");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
/*
* 判斷檔案型別
*/
private boolean judgeFileType(String[] types,String type){
booleanresult = false;
for (String typeStr : types) {
if (typeStr.equals(type)) {
result = true;
break;
}
}
returnresult;
}
}
/***
* 隨機產生檔案的名稱
* fileItem.write(new File("/DevelopTool/eclipseworkplace/theaddressbook/WebContent/resources/images/" + UUID.randomUUID().toString() + "." + fileExt));
*
*/