JSP + servlet 源碼 實現檔案的上傳

來源:互聯網
上載者:User

標籤: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 源碼 實現檔案的上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.