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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSP + servlet 源码 实现文件的上传相关的知识,希望对你有一定的参考价值。

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 源码 实现文件的上传的主要内容,如果未能解决你的问题,请参考以下文章

JSP+Servlet+C3P0+Mysql实现的azhuo商城

servlet+jsp实现的文件上传与下载

JSP 实用程序之简易文件上传组件

jsp使用servlet实现文件上传

jsp+servlet怎么实现文件断点上传下载

Java jsp servlet 实现文件上传 最简单操作