Servletはファイルのアップロードとダウンロードを実現します。

10214 ワード

この時間にウェブプロジェクトを書いてみました。ファイルのアップロードとダウンロードに関しては、ネット上には多くの成熟したフレームがありますが、学習のために自分で関連コードを作成しました。この中で多くの問題が発生しましたので、ここで完全なアップロードとダウンロードコードを共有します。
まずアップロードされたServletコードです。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.util.Random;

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

public class UpLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final Random RANDOM = new Random();		
	private String tempFileFolder;	//        
	private String fileFolder;	//      

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//step 1              
		File tempFile = getTempFile();
		writeToTempFile(request.getInputStream(), tempFile);
		
		//step 2             
		RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
		
		//step 3      
		String filename = getFileName(randomFile);
		
		//step 4            
		checkFold();
		
		//step 5    
		long fileSize = saveFile(randomFile, filename);
		
		//step 6     ,      
		randomFile.close();
		tempFile.delete();
		
	}

	public void init() throws ServletException {
		//        
		String contentPath = getServletContext().getRealPath("/");
		this.tempFileFolder = contentPath + "files/_tmp";
		this.fileFolder = contentPath+"files/_file";
	}
	
	
	/**
	 *         
	 * @param str
	 * @return        
	 */
	private String codeString(String str) {
		String s = str;
		try {
			byte[] temp = s.getBytes("ISO-8859-1");
			s = new String(temp, "UTF-8");
			return s;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return s;
		}
	}
	
	/**
	 *         
	 *            ,          
	 * @return       
	 * @throws IOException
	 */
	private File getTempFile()throws IOException{
		File tempFolder = new File(this.tempFileFolder);
		if (!tempFolder.exists()){
			tempFolder.mkdirs();
		}
		String tempFileName = this.tempFileFolder+File.separator+Math.abs(RANDOM.nextInt());
		File tempFile = new File(tempFileName);
		if (!tempFile.exists()){
			tempFile.createNewFile();
		}
		return tempFile;
	}
	
	/**
	 *              
	 * @param fileSourcel    
	 * @param tempFile	          
	 * @throws IOException
	 */
	private void writeToTempFile(InputStream fileSourcel,File tempFile)throws IOException{
		FileOutputStream outputStream = new FileOutputStream(tempFile);
		byte b[] = new byte[1000];
		int n ;
		while ((n=fileSourcel.read(b))!=-1){
		    outputStream.write(b,0,n);
		}
		outputStream.close();
		fileSourcel.close();
	}
	
	/**
	 *              
	 * @param randomFile
	 * @return        
	 * @throws IOException
	 */
	private String getFileName(RandomAccessFile randomFile)throws IOException{
		String _line;
		while((_line=randomFile.readLine())!=null && !_line.contains("form-data; name=\"upload\"")){
		}
		String filePath = _line;
		String filename = filePath.replace("Content-Disposition: form-data; name=\"upload\"; filename=\"", "").replace("\"","");
		
		filename=codeString(filename);
		randomFile.seek(0);
		return filename;
	}
	
	/**
	 *            
	 *        from           
	 *   from              
	 *   from      title input ,         。          。
	 * @param randomFile
	 * @return          
	 * @throws IOException
	 */
	private long getFileEnterPosition(RandomAccessFile randomFile)throws IOException{
		long  enterPosition = 0;
		int forth = 1;
		int n ;
		while((n=randomFile.readByte())!=-1&&(forth<=8)){
		    if(n=='
'){ enterPosition = randomFile.getFilePointer(); forth++; } } return enterPosition; } /** * * , * * @param randomFile * @return * @throws IOException */ private long getFileEndPosition(RandomAccessFile randomFile)throws IOException{ randomFile.seek(randomFile.length()); long endPosition = randomFile.getFilePointer(); int j = 1; while((endPosition>=0)&&(j<=2)){ endPosition--; randomFile.seek(endPosition); if(randomFile.readByte()=='
'){ j++; } } return endPosition; } /** * */ private void checkFold(){ File file = new File(this.fileFolder); if (!file.exists()){ file.mkdirs(); } } /** * * @param randomFile * @param forthEnterPosition * @param filename * @return fileSize * @throws IOException */ private long saveFile(RandomAccessFile randomFile,String filename)throws IOException{ File saveFile = new File(this.fileFolder,filename); RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw"); long forthEnterPosition = getFileEnterPosition(randomFile); long endPosition = getFileEndPosition(randomFile); // , randomFile.seek(forthEnterPosition); long startPoint = randomFile.getFilePointer(); while(startPoint<endPosition){ randomAccessFile.write(randomFile.readByte()); startPoint = randomFile.getFilePointer(); } long fileSize = randomAccessFile.length(); randomAccessFile.close(); return fileSize; } }
次はダウンロードのServletコードです。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

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

public class Download extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String FILEDIR="files/_file";
	private String fileFolder;	//      
	
	public Download() {
		super();
	}

	
	public void destroy() {
		super.destroy(); 
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		request.setCharacterEncoding("UTF-8");
		try{
			String fileName = request.getParameter("name");
			OutputStream outputStream = response.getOutputStream();
			//          ,        600   
			byte b[] = new byte[600];
			
			File fileload = new File(this.fileFolder,fileName);
			
			fileName=encodeFileName(request,fileName);
			//             
			response.setHeader("Content-disposition", "attachment;filename="+fileName);
			//         
			long fileLength = fileload.length();
			String length = String.valueOf(fileLength);
			response.setHeader("Content_length", length);
			//    ,         
			FileInputStream inputStream = new FileInputStream(fileload);
			int n = 0;
			while((n=inputStream.read(b))!=-1){
			    outputStream.write(b,0,n);
			}
		}catch(FileNotFoundException fnfe){
			fnfe.printStackTrace();
			try{
				PrintWriter out = response.getWriter();
				out.println("        ");
				out.flush();
				out.close();
			}catch(IOException ie){
				ie.printStackTrace();
			}
		}catch(IOException ie){
			ie.printStackTrace();
			try{
				PrintWriter out = response.getWriter();
				out.println("      ");
				out.flush();
				out.close();
			}catch(IOException iex){
				iex.printStackTrace();
			}
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		this.fileFolder = getServletContext().getRealPath("/")+"files/_file";
	}
	
	private String encodeFileName(HttpServletRequest request,String fileName){
		try{
			//IE
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") >0){
				fileName=URLEncoder.encode(fileName,"UTF-8");
			}else{
				fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return fileName;
	}
	
}