Java两台服务器之间传递文件
Java两台服务器之间传递⽂件[quote]⽤HttpClient来模拟POST提交表单[/quote]
[quote]发送端进⾏提交的⽅法[/quote]
package com.wangyp.demo;
import java.io.InputStream;
import org.apachemons.httpclient.DefaultMethodRetryHandler;
import org.apachemons.httpclient.HttpClient;
import org.apachemons.httpclient.NameValuePair;
import org.hods.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("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");
// Params().setContentCharset("GB2312");
DefaultMethodRetryHandler retryhandler = new DefaultMethodRetryHandler();
retryhandler.setRequestSentRetryEnabled(false);
retryhandler.setRetryCount(10);
method.setQueryString(nvp);
method.InputStream());
method.setMethodRetryHandler(retryhandler);
InputStream is = ResponseBodyAsStream();
NameValuePair pair = Parameter("");
String status = Value();
}
}
[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 = Resource("/").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();
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。