在我们的工作中常常有一些需求,需要文件和服务器分离。将一些图片,音乐,等一些大文件放在其余的服务器上,多台服务器协作。在网上找了很多代码,都没有达到我的要求。这段时间一直在研究这个问题。废话不多说了,上代码。

//上传本地文件到服务器
// String url = "C:\\Users\\esen\\Desktop\\sun.m4a";
// File file = new File(url);
// byte[] buf = FileUtils.readFileToByteArray(file);

//远程文件地址,想要上传本地文件,看上面的方法。
URL ss = new URL(
"http://song.music.response.itmf.cn/794f4b5e86df8dbf83700f32541f8cbc/57c545a7/G007/M01/1A/04/Rw0DAFS2CQGANeLaABKVEk0zum0928.m4a");
HttpURLConnection urlc = (HttpURLConnection) ss.openConnection();
urlc.setDoInput(true);// 设置是否要从 URL 连接读取数据,默认为true
urlc.connect();
InputStream bufin = urlc.getInputStream();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
int len = bufin.available();
byte[] b = new byte[len];
int rc = 0;
while ((rc = bufin.read(b, 0, len)) > 0) {
swapStream.write(b, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
// 实例化Jersey
Client client = new Client();

//想要发送到的服务器地址,记住,必须设置tomcat服务器的权限,不然无法上传到tomcat

String path = "http://localhost:8080/music/music/sunaa.m4a";
// 设置请求路径
WebResource resource = client.resource(path);
// 发送开始 PUT
try {
resource.put(String.class, in2b);
System.out.println(7);
} catch (Exception e) {
e.printStackTrace();
}

到这里就成功了

posted on 2016-08-30 17:06  石头ren  阅读(937)  评论(0编辑  收藏  举报