java三种方式实现文件的上传

1:

实现文件的上传可以有好多途径,最简单的就是用sun公司提供的File类,可以简单的实现文件的上传和显示:

try {

InputStream stream = file.getInputStream();//把文件读入

Savefilepath = request.getRealPath("/upload");//将文件存放在当前系统路径的哪个文件夹下

Savefilename = getNewFilename(file.getFileName());

Savefilepath = Savefilepath + "\\" + Savefilename;

OutputStream bos = new FileOutputStream(Savefilepath);//建立一个上传文件的输出流

int bytesRead = 0;

byte[] buffer = new byte[10*1024];

while ( (bytesRead = stream.read(buffer, 0, 10240)) != -1) {

bos.write(buffer, 0, bytesRead);//将文件写入服务器的硬盘上

}

bos.close();

stream.close();

}catch(Exception e){

e.printStackTrace();

}

2:

简单的代码如下,于此同时有一个很简单的扩展的jspsmart很好用,他是封装好的一些上传的组建,做一些上传的优化,下面就是简单实现上传的例子:

上传页面:
<html>
 <head>
 <title>smartupload</title>
 </head>
 
 <body>
 <form action="smartupload02.jsp" method="post" enctype="multipart/form-data">
 上传的图片:<input type="file" name="pic">
 <input type="submit" value="上传">
 </form>
 </body>
</html>

处理页面:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/>

<html>

<head>

<title>smartupload</title>

</head>

<body>

<%

smartupload.initialize(pageContext) ; // 初始化上传

smartupload.upload() ; // 准备上传

smartupload.save("upload") ; // 保存文件

%>

</body>

</html>

3:

最后就是servlet3.0的新特性里面的上传文件的新特性,他则是采用part来实现的,下面是简单的例子:

package com.simple;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.Part;

import com.sun.xml.ws.wsdl.parser.Part;

public class uploadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

Part part = request.getPath("file");

String name = part.getName();

String url = request.getSession().getServletContext().getRealPath("/upload");

String reqName = request.getHeader("content-disposition");

String fileName = reqName.substring(reqName.lastIndexOf("=")+2, reqName.length()-1);

part.write(url+"/"+fileName);

}

}

其实功能是一样的,要求也就是以实现功能为宗旨,但是多学习点东西总是好的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值