码迷,mamicode.com
首页 > Web开发 > 详细

JSP + servlet 源码 实现文件的上传

时间:2017-03-04 12:52:16      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:rpo   ext   import   读取文件   meta   response   output   dispatch   名称   

JSP页面

 upLoad.jsp

_________________________________

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>uoLoad</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
 <form action="MyUpLoadServlet" method="post"
  enctype="multipart/form-data">  
  请选择文件:<input id="myfile" name="myfile" type="file"
   onchange="showPreview(this)" /> <input type="submit" value="提交" />${result}
 </form>

</body>
</html>

servlet

package com.agd.servlet;

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

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


@WebServlet("/MyUpLoadServlet")
public class MyUpLoadServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
        
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  //开始位置
  
  String image="image";
  copy2(request, image);
  
  
  
  //结束位置
  request.setAttribute("result", "上传成功!");
  RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
  dispatcher.forward(request, response);
  }
  

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  doGet(request, response);
 }
   
 protected  void copy2(HttpServletRequest request,String url ) throws ServletException, IOException {
  //从request当中获取流信息
  InputStream fileSource=request.getInputStream();
  String tempFileName="E:/tempFile";
  //指向临时文件
  File tempFile=new File(tempFileName);
  //outPutStream 文件输出流指向这个临时文件
  @SuppressWarnings("resource")
  FileOutputStream outputStream=new FileOutputStream(tempFile);
  //开始读写数据
  byte[] b=new byte[1024];
  int len=0;
  while((len=fileSource.read(b))!=-1){
   outputStream.write(b, 0, len);
  }
  //关闭输出流输入流
  outputStream.close();
  fileSource.close();
  System.out.println("上传成功");
  //获取文件上传的名称
  RandomAccessFile randomFile=new RandomAccessFile(tempFile, "r");
  randomFile.readLine();//读取第一行数据
  String str=randomFile.readLine();//读取第二行数据

//临时文件第一行和最后一行都是不需要的

 


  System.out.println(str);
  String str1=str.substring(0,str.lastIndexOf("\""));//根据最后一个引号来定位
  System.out.println(str1);
  int endIndex=str.lastIndexOf("\"");
  int beginIndex=str1.lastIndexOf("\"")+1;//beginIndex,endIndex得到文件name的初始位置
  String filename=str.substring(beginIndex,endIndex);
  filename=new String(filename.getBytes("ISO-8859-1"),"utf-8");
  System.out.println("filename"+filename);
  //重新定位文件指针到文件头
  randomFile.seek(0);
  long startPosition=0;
  int i=1;
  byte n;
  //获取文件内容,开始位置
  while((n=randomFile.readByte())!=-1&&i<=4){
  if(n==‘\n‘){
   startPosition=randomFile.getFilePointer();//getFilePointer()用于定位
   i++;
  } 
   
  }
  startPosition = randomFile.getFilePointer() -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 realPath =getServletContext().getRealPath("/") + url;//为文件保存的绝对路径
  System.out.println(realPath);
  
  File fileupload = new File(realPath);
  
  if(!fileupload.exists()){
  fileupload.mkdir();
  }
  File saveFile = new File(realPath,filename);
  RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
  //从临时文件当中读取文件内容(根据起止位置获取)
  randomFile.seek(startPosition);
  while(startPosition < endPosition){
  randomAccessFile.write(randomFile.readByte());
  startPosition = randomFile.getFilePointer();
  }
  System.out.println("最终版成功");
  //关闭输入输出流、删除临时文件
  randomAccessFile.close();
  randomFile.close();
  tempFile.delete(); //删除临时文件,
 } 
}

JSP + servlet 源码 实现文件的上传

标签:rpo   ext   import   读取文件   meta   response   output   dispatch   名称   

原文地址:http://www.cnblogs.com/Mr-lixf/p/6500896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!