HTTP API进行文件上传的时候,如何把文件转换为二进制,怎么上传?
发布于 6 年前 作者 junduan 11960 次浏览 来自 问答

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

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();
				}
		} 

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

回到顶部