java从服务器下载文件_java web 肿么从服务器下载文件到客户端的指定位置

这个很简单啊,就是定义一个input file类型的,然后上传,获取上传的文件,用inputstream读取,然后用outputstream写入到你服务器的指定位置就行了。如果用struts来接收上传文件就简单了,只需要命名和jsp文件input file类型名称相同的字段就能获取上传文件了,file类型的。

/** 新闻代表图片 */

private File newsPicture;//文件字段和jsp 中文件name相同

private String newsPictureFileName;//文件名称,可以自动获取

private String newsPictureContentType;//文件类型,可以自动判断

//上传的共用方法,srcFile源文件,savePath保存的路径,fileName文件名称,你使用这个方法就可以上传了。

public static File uploadUtil(File srcFile,String savePath,String FileName){

InputStream is = null;

OutputStream os = null;

File toFile = null;

if(srcFile!=null){

try {

is = new FileInputStream(srcFile);

String fileName = (new Date().getTime())+FileName.substring(FileName.indexOf("."));

toFile = new File(ServletActionContext.getServletContext().getRealPath(savePath), fileName);

os = new FileOutputStream(toFile);

byte[] buffer = new byte[1024];

int length = 0;

while ((length = is.read(buffer)) > 0) {

os.write(buffer, 0, length);

}

os.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

try {

is.close();

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return toFile;

}

取消

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值