Java 两台服务器之间传递文件

[quote]用HttpClient来模拟POST提交表单[/quote]

[quote]发送端进行提交的方法[/quote]
package com.wangyp.demo;

import java.io.InputStream;

import org.apache.commons.httpclient.DefaultMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.struts.upload.FormFile;

public class SendImageService {
/**
* 此方法是根据FormFile编写的,可以自定义图片名称.如果接收端设定连接时需要用户名和密码则需要填写用户名与密码
*
* @param ff
* FormFile
* @param ImageName
* 图片名称
* @throws Exception
*/
public static void sendImage(FormFile ff, String ImageName) throws Exception {
HttpClient hc = new HttpClient();

PostMethod method = new PostMethod("http://192.168.0.156:8081/memo_ReceiveImages/receiveImages.do");
NameValuePair[] nvp = { new NameValuePair("ImageName", ImageName), new NameValuePair("username", "baoku"),
new NameValuePair("password", "19840523") };

method.addRequestHeader("Content-Type", "text/html;charset=UTF-8");
// method.getParams().setContentCharset("GB2312");
DefaultMethodRetryHandler retryhandler = new DefaultMethodRetryHandler();

retryhandler.setRequestSentRetryEnabled(false);

retryhandler.setRetryCount(10);

method.setQueryString(nvp);
method.setRequestBody(ff.getInputStream());
method.setMethodRetryHandler(retryhandler);

hc.executeMethod(method);

InputStream is = method.getResponseBodyAsStream();

NameValuePair pair = method.getParameter("");

String status = pair.getValue();
}
}

[quote]接收端进行接收的方法[/quote]
package com.wangyp.struts.service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ReceiveImageImpl {

/**
* 根据文件流的方式来获取传递的图片,可以设定图片名称
*
* @param is
* IO流
* @param ImageName
* 图片名称
* @return
* @throws Exception
*/
public static void receiveImage(InputStream is, String ImageName) throws Exception {
OutputStream os = null;
try {
String path = ReceiveImageImpl.class.getResource("/").toString().replace("file:/", "").replace("classes/",
"").replace("/WEB-INF", "")
+ "Image/" + ImageName + ".jpg";

os = new FileOutputStream(path);

// 8k缓存数据
byte[] buffer = new byte[1024 * 8];
// 设置读进缓存的字节数
int len;
while ((len = is.read(buffer)) != -1) {
// 将缓存数据写入磁盘
os.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭输出流
os.close();
// 关闭输入流
is.close();
}
}
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值