java上传文件三种方式

实现文件的上传可以有好多途径,最简单的就是用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);

    }

}

猜你喜欢

转载自jinlovejava.iteye.com/blog/2120102