iOS图片上传服务器(ASIHTTPRequest,SpringMVC)

最近开始做自己app的服务器,因为正在参与的公司项目用的是springMVC,干脆拿这个做服务器,iOS端采用第三方鼎鼎大名的ASIHTTPRequest(但是已停更很久),经过一天折腾,终于实现简单的图片上传

  1. 配置ASIHTTPRequest,参见
    ASIHTTPRequest配置说明
  2. 搭建简单的springMVC环境

  3. 代码

    iOS端:

-(void)uploadImgToServer:(UIImage*)image{
    ASIFormDataRequest *formDataRequest=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://tyrantkemp.imwork.net:21848/mvc1/helloworld/uploadfile"]];
    [formDataRequest setPostValue:@"hahaha" forKey:@"name"];
    NSData *postData=UIImageJPEGRepresentation(image, 3);
    if(postData==nil){
        NSLog(@"pic data为空!!!");
    }
    [formDataRequest setDelegate:self];
    [formDataRequest addData:postData forKey:@"file"];
    NSLog(@"pic data:%@",formDataRequest);
    [formDataRequest setDidFailSelector:@selector(urlRequestFailed:)];
    [formDataRequest setDidFinishSelector:@selector(urlRequestSucceeded:)];
    [formDataRequest startSynchronous];
   // NSLog(@"responce is %@",[formDataRequest responseString]);

}
//请求失败
-(void)urlRequestFailed:(ASIHTTPRequest *)request
{
    NSError *error =[request error];
    NSLog(@"%@",error);
    NSLog(@"连接失败!");
    UIAlertView * alt=[[UIAlertView alloc] initWithTitle:@"提示" message:@"连接服务器失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alt show];
}

//请求成功
-(void)urlRequestSucceeded:(ASIHTTPRequest *)request
{
    NSData *data=[request responseData];
    NSXMLParser *parser=[[NSXMLParser alloc] initWithData:data];
    NSLog(@"data length = %d",[data length]);
    NSLog(@"xml data = %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [parser setDelegate:self];
    [parser parse];//进入解析
}

springmvc端:

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST) 
public String handleFileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws FileUploadException{
         long startTime=System.currentTimeMillis();   //获取开始时间  
         if(!file.isEmpty()){  
             try {  

                 File ouputimage = new File("C:/pic/green2.jpg"); //新建一个文件
                 try {
                 file.getFileItem().write(ouputimage); //将上传的文件写入新建的文件中
                 } catch (Exception e) {
                   e.printStackTrace();
                 }

             }catch(Exception e){
                 e.printStackTrace();
             }

         }
         long endTime=System.currentTimeMillis(); //获取结束时间  
         System.out.println("上传文件共使用时间:"+(endTime-startTime));  
         return "success"; 
    }
上一篇:【iOS7的一些总结】7、键值观察者模式KVO


下一篇:jQuery之工具函数