收藏
回答

HTTP API进行文件上传的时候,如何把文件转换为二进制,怎么上传?

在上传文件拼装时,文件二进制内容怎么获取啊

public static byte[] fileToByte(String filepath) throws IOException{
		byte[] bytes = null;
		FileInputStream fis = null;
		try{
			File file = new File(filepath);
			fis = new FileInputStream(file);
			bytes = new byte[(int) file.length()];
			fis.read(bytes);
		}catch(IOException e){
			e.printStackTrace();
			throw e;
		}finally{
			fis.close();
		}
		return bytes;
	}

这样对吗?然后我在上传的时候传不进去。

byte[] er=fileToByte("D:\\provinceCode.json");
		for(int i=0;i<er.length;i++)
	   	{
			System.out.println(er[i]);
	   	}
		Date date=new Date();
		SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
		String dateString = format.format(date);
		String strURL =file.get("url");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("key", "provinceCode.json");
		paramMap.put("Signature", file.get("authorization")); 
		paramMap.put("x-cos-security-token", file.get("token")); 
		paramMap.put("x-cos-meta-fileid", file.get("cos_file_id")); 
		paramMap.put("file", er);
		OutputStreamWriter out = null;
		try { 
			URL url = new URL(strURL);// 创建连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true); 
			connection.setDoInput(true);
			connection.setUseCaches(false); 
			connection.setInstanceFollowRedirects(true);
			  connection.setRequestMethod("POST"); // 设置请求方式
			  connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
			  connection.setRequestProperty("Content-Type", "application/json"); //设置发送数据的格式
			  connection.connect(); 
			  out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
			  String json = JSON.toJSONString(paramMap); 
			  out.append(json); 
			  out.flush();
			  out.close(); 
			
		} catch (IOException e) { 
			e.printStackTrace();
		} finallytry { 
				
				out.close(); 
			} catch (IOException e) {
				e.printStackTrace();
				}
		} 

哪里出问题了啊!!!跪求大佬们帮忙!!!

回答关注问题邀请回答
收藏

1 个回答

  • Mr.Zhao
    Mr.Zhao
    发表于小程序端
    2020-05-29

    2020-05-29
    有用
    回复 2
    • 老圈
      老圈
      2020-05-29
      谢谢大佬
      2020-05-29
      回复
    • Mr.Zhao
      Mr.Zhao
      2020-05-29回复老圈
      已补充
      2020-05-29
      回复
登录 后发表内容
问题标签