hessian系列之二:上传文件

hessian较早版本通过 byte[] 进行文件传输;4.0之后支持 InputStream 作为参数或返回值进行传输。

注意:hessian会读取整个文件,如果文件过大,会导致JVM内存溢出。可以通过控制上传文件的大小,设置合理的JVM参数,以及采用随机读取方式来解决。


[size=medium]1. 接口:[/size]

一般放在独立的工程中,供服务端和客户端引用


public interface Uploader {
void upload(String filename, InputStream data);
}


[size=medium]2. 服务端:[/size]

[b]实现类[/b]:

public class FileUploader implements Uploader {

private static final Logger logger = LoggerFactory.getLogger(FileUploader.class);

@Override
public void upload(String filename, InputStream data) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(data);
bos = new BufferedOutputStream(new FileOutputStream("D:\\upload\\" + filename));
byte[] buffer = new byte[8192];
int r = bis.read(buffer, 0, buffer.length);
while (r > 0) {
bos.write(buffer, 0, r);
r = bis.read(buffer, 0, buffer.length);
}
} catch (IOException e) {
logger.error("File upload exception: ", e);
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
logger.error("Closing output exception: ", e);
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
logger.error("Closing input exception: ", e);
}
}
}
}
}


[b]web.xml[/b]

<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<param-name>home-class</param-name>
<param-value>com.john.hessian.impl.FileUploader</param-value>
</init-param>
<init-param>
<param-name>home-api</param-name>
<param-value>com.john.hessian.intf.Uploader</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>


在浏览器地址栏输入:http://localhost/hessian/upload,查看是否可以调用。

[size=medium]3. 客户端:[/size]
[b]测试类[/b]:

public class FileUploaderTest {

static final String url = "http://localhost/hessian/upload";

@Test
public void testFileUploader() throws MalformedURLException, FileNotFoundException {
HessianProxyFactory factory = new HessianProxyFactory();
Uploader uploader = (Uploader) factory.create(Uploader.class, url);
InputStream data = new BufferedInputStream(new FileInputStream("D:\\test.7z"));
uploader.upload("test.7z", data);
}
}


依次启动服务端和客户端,查看指定文件是否上传成功。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值