天天看點

java上傳檔案三種方式

實作檔案的上傳可以有好多途徑,最簡單的就是用sun公司提供的File類,可以簡單的實作檔案的上傳和顯示:

try {

InputStream stream = file.getInputStream();//把檔案讀入

Savefilepath = request.getRealPath("/upload");//将檔案存放在目前系統路徑的哪個檔案夾下

Savefilename = getNewFilename(file.getFileName());

Savefilepath = Savefilepath + "\\" + Savefilename;

OutputStream bos = new FileOutputStream(Savefilepath);//建立一個上傳檔案的輸出流

int bytesRead = 0;

byte[] buffer = new byte[10*1024];

while ( (bytesRead = stream.read(buffer, 0, 10240)) != -1) {

bos.write(buffer, 0, bytesRead);//将檔案寫入伺服器的硬碟上

}

bos.close();

stream.close();

}catch(Exception e){

e.printStackTrace();

}

2:

簡單的代碼如下,于此同時有一個很簡單的擴充的jspsmart很好用,他是封裝好的一些上傳的組建,做一些上傳的優化,下面就是簡單實作上傳的例子:

上傳頁面:

<html>

<head>

<title>smartupload</title>

</head>

<body>

<form action="smartupload02.jsp" method="post" enctype="multipart/form-data">

上傳的圖檔:<input type="file" name="pic">

<input type="submit" value="上傳">

</form>

</body>

</html>

處理頁面:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/>

<html>

<head>

<title>smartupload</title>

</head>

<body>

<%

smartupload.initialize(pageContext) ; // 初始化上傳

smartupload.upload() ; // 準備上傳

smartupload.save("upload") ; // 儲存檔案

%>

</body>

</html>

3:

最後就是servlet3.0的新特性裡面的上傳檔案的新特性,他則是采用part來實作的,下面是簡單的例子:

package com.simple;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.Part;

import com.sun.xml.ws.wsdl.parser.Part;

public class uploadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

Part part = request.getPath("file");

String name = part.getName();

String url = request.getSession().getServletContext().getRealPath("/upload");

String reqName = request.getHeader("content-disposition");

String fileName = reqName.substring(reqName.lastIndexOf("=")+2, reqName.length()-1);

part.write(url+"/"+fileName);

}

}