Java、ios图片上传

1 篇文章 0 订阅

IOS客服端代码

@interface ViewController ()
{
    NSString *boundary;
    NSString *fileParam;
    NSString *baseUrl;
    NSString *fileName;
}
@end

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
	boundary = @"----------V2ymHFg03ehbqgZCaKO6jy";
    fileParam = @"file";
    baseUrl = @"http://url/from/server";
    fileName = @"image.png";//此文件提前放在可读写区域
}
//请求方法
-(void)method4{
    NSURL *uploadURL;
    //文件路径处理(随意)
    NSLog(@"请求路径为%@",uploadURL);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
        //body
        NSData *body = [self prepareDataForUpload];
        //request
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
        [request setHTTPMethod:@"POST"];
        
        // 以下2行是关键,NSURLSessionUploadTask不会自动添加Content-Type头
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
        
        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
            
            NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"message: %@", message);
            
            [session invalidateAndCancel];
        }];
        
        [uploadTask resume];
    });
}
//生成bodyData
-(NSData*) prepareDataForUpload
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *uploadFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];<span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 17.600000381469727px; ">//将图片放在了documents中</span><span style="margin: 0px; padding: 0px; border: none; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 17.600000381469727px; ">  </span>
    
    NSString *lastPathfileName = [uploadFilePath lastPathComponent];
    
    NSMutableData *body = [NSMutableData data];
    
    NSData *dataOfFile = [[NSData alloc] initWithContentsOfFile:uploadFilePath];
    
    if (dataOfFile) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:dataOfFile];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    return body;
}

Java服务器端代码

@RequestMapping(value = "/member/headPic/save",method = RequestMethod.POST)
public void saveMemberHeadPic(HttpServletRequest request,HttpServletResponse response,
									  @RequestParam("token") String token){
	//创建一个临时文件存放要上传的文件,第一个参数为上传文件大小,第二个参数为存放的临时目录
			DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024*5,new File("D:\\temp1"));
			// 设置缓冲区大小为 5M
			factory.setSizeThreshold(1024 * 1024 * 5);
			// 创建一个文件上传的句柄
			ServletFileUpload upload = new ServletFileUpload(factory);

			//设置上传文件的整个大小和上传的单个文件大小
			upload.setSizeMax(1024*1024*50);
			upload.setFileSizeMax(1024*1024*5);
			String[] fileExts = {"doc","zip","rar","jpg","txt"};
			try { //把页面表单中的每一个表单元素解析成一个
				FileItem List<FileItem> items = upload.parseRequest(request);
				for (FileItem fileItem : items) {
					//如果是一个普通的表单元素(type不是file的表单元素)
					if(fileItem.isFormField()){ 
						System.out.println(fileItem.getFieldName());
					//得到对应表单元素的名字
					 System.out.println(fileItem.getString());
					// 得到表单元素的值
					}else{ //获取文件的后缀名
						 String fileName = fileItem.getName();//得到文件的名字
						 String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
						 if(Arrays.binarySearch(fileExts, fileExt)!=-1){
							try { //将文件上传到项目的upload目录并命名,getRealPath可以得到该web项目下包含/upload的绝对路径//
								fileItem.write(new File(request.getServletContext().getRealPath("/upload")+"/" + UUID.randomUUID().toString()+"."+fileExt));
								fileItem.write(new File("D:/test2.png"));
								 logger.info("文件上传路径:"+request.getServletContext().getRealPath("/upload")+"/" + UUID.randomUUID().toString()+"."+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(); 
			}
	}






 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值