iOS ASIFormDataRequest上传图片 前后台代码

1 篇文章 0 订阅
iOS 表单格式上传图片
NSString *urls = NSLocalizedString(@"Service_url_upload_do_json", @"");
    NSURL *url = [[NSURL alloc] initWithString: urls];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setDelegate :self];
    NSString *res = @"http://f.hiphotos.baidu.com/image/pic/item/58ee3d6d55fbb2fb9ecd3a1b4d4a20a44723dcd1.jpg";
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:[[NSURL alloc] initWithString:res]];
    [request setRequestMethod:@"POST"];
    
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSString *key=@"smx";
    //添加分界线,换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //添加字段名称,换2行
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
    //添加字段的值
    [body appendFormat:@"%@\r\n",@"测试"];
    
    添加分界线,换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段,文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"test.jpg\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符:--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData,用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:imageData];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"Multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    
    [request addRequestHeader:@"Content-Type" value:content];
    //设置http body
    [request setPostBody:myRequestData];
    [request startAsynchronous];

 

java处理上传图片

public class FileUploadImpl implements ServletRequestAware,
		ServletResponseAware {


	private final static Logger logger = Logger.getLogger(FileUploadImpl.class);
	protected HttpServletRequest request;
	protected HttpServletResponse response;


	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub


		this.request = arg0;
	}


	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}


	/**
	 * 处理上传文件
	 * 
	 * @param request
	 * @throws UnsupportedEncodingException
	 */
	public void executeUpload() {
		logger.info("=======executeUpload");
		DataOutputStream output = null;
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		try {
			output=new DataOutputStream(response.getOutputStream());


			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart == true) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				List fileItems = upload.parseRequest(request); // 得到所有的表单域,它们目前都被当作FileItem
				logger.info("fileItems==="+fileItems.size());
				String uploadPath = ValueTable.getInstance(false).GetValue(
						"MobileUploadPath");
				String ffmpegPath = ValueTable.getInstance(false).GetValue(
						"ffmpegPath");
				File file = new File(uploadPath);
				if (!file.exists()) { // 如果没有此目录就创建此目录
					file.mkdir();
				}
				int faultid = 0;
				Iterator<FileItem> iter = fileItems.iterator();

				while (iter.hasNext()) { // 依次处理每个表单域
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) { // 如果item是正常的表单域
						
					} else { // 如果item是文件上传表单域
						String filename = item.getName();
						// 得到文件名
						String filetype = filename.substring(
								filename.lastIndexOf(".") + 1,
								filename.length()); // 文件后缀
						InputStream is = item.getInputStream(); // 此处已经得到上传文件的输入流
						String filepath = uploadPath + filename; // 此处的filename可以改名存储
						if (new File(filepath).exists()) { // 上传文件是否存在
							new File(filepath).delete(); // 存在就删除
						}
						if (!filepath.equals("")) { // 如果文件名不为空
							FileOutputStream fos = new FileOutputStream(
									filepath);
							byte[] buffer = new byte[10240];
							int count = 0;
							while ((count = is.read(buffer)) > 0) {
								fos.write(buffer, 0, count); // 开始上传至目录文件
							}
							fos.close();
							is.close();


							// 文件已经生成 开始执行转换线程
							if (如果是视频 转成flv格式) {
							
							<span style="white-space:pre">	</span>String convertDestPath = uploadPath
										+ filename.substring(0,
												filename.lastIndexOf(".") + 1)
										+ "flv";
								try {
									ConvertVideo convertVideo = new ConvertVideo(
											filepath, convertDestPath,
											ffmpegPath);
									boolean b = convertVideo.process();
								} catch (Exception e) {
									e.printStackTrace();
								}

						}
					}
				}
				output.write("".getBytes("utf-8")); 
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} try {
     	   output.flush();
     	   output.close(); 
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值