通过JSP+servlet实现文件上传功能

     在TCP/IP中,最早出现的文件上传机制是FTP.它将文件由客户端到服务器的标准机制。

     但是在JSP中不能使用FTP来上传文件,这是有JSP的运行机制所决定的。

     通过为表单元素设置Method="post" enctype="multipart/form-data" 属性,让表单提交的数据以二进制编码的方式提交,在接受此请求的servlet中的二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。

代码分两部分

part1:前台页面index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>
  </head>
  
  <body>
    <form action="UploadFile" method="post" enctype="multipart/form-data">
    <table>
    <tr>
    <td align="center">
               请选择上传的文件:<input type="file" name="fileName"/>
&nbsp;&nbsp;<input type="submit" value="上传"/>${result}
</td> </tr> </table> </form> </body> </html>

part2:servlet代码

package com.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploadFile extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        doPost(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        //写入缓存文件
        InputStream fileSource=request.getInputStream();
        String tempFileName="E:/tempFile";
        File tempFile=new File(tempFileName);
        FileOutputStream outputStram=new FileOutputStream(tempFile);
        byte[] b=new byte[1024];
        int n;
        while((n=fileSource.read(b))!=-1){
            outputStram.write(b,0,n);
        }        
        outputStram.close();
        fileSource.close();
        System.out.println("成功");
        
        //获取文件名
        RandomAccessFile randomFile=new RandomAccessFile(tempFile,"r");
        randomFile.readLine();
        String str=randomFile.readLine();
        int beginIndex=str.lastIndexOf("\\")+1;
        int endIndex=str.lastIndexOf("\"");
        String filename=str.substring(beginIndex, endIndex);
        System.out.println("filename:"+filename);

//获取上传文件内容的开始位置 randomFile.seek(
0); long startPosition=0; int i=1; while((n=randomFile.readByte())!=-1&&i<=4){ if(n=='\n'){ startPosition=randomFile.getFilePointer(); i++; } } startPosition=startPosition-1;
//获取上传文件内容的结束位置
randomFile.seek(randomFile.length());
long endPosition=randomFile.getFilePointer(); int j=1; while(endPosition>=0&&j<=2){ endPosition--; randomFile.seek(endPosition); if(randomFile.readByte()=='\n'){ j++; } } endPosition=endPosition-1;
//上传文件
String path=getServletContext().getRealPath("/")+"MyImages"; //指定上传文件的目录
File fileupload=new File(path); if(!fileupload.exists()){ fileupload.mkdir(); } File saveFile=new File(path,filename); RandomAccessFile RAF=new RandomAccessFile(saveFile,"rw"); randomFile.seek(startPosition); while(startPosition<endPosition){ RAF.write(randomFile.readByte()); startPosition=randomFile.getFilePointer(); } RAF.close(); randomFile.close(); tempFile.delete(); request.setAttribute("result","上传成功!"); RequestDispatcher dispatcher=request.getRequestDispatcher("index.jsp"); dispatcher.forward(request,response); } }

 

posted @ 2015-05-13 11:34  Json_wangqiang  阅读(641)  评论(0编辑  收藏  举报