ラベル JSP の投稿を表示しています。 すべての投稿を表示
ラベル JSP の投稿を表示しています。 すべての投稿を表示

2010年8月14日土曜日

JSP/サーブレットでファイルをアップロードするには?

JSP/サーブレットでファイルをアップロードするには、
従来は非常に煩雑なコーディングが必要となっていました。
そこで簡単にできるパッケージとしてJakarta Commons のサブプロジェクトにある
upload.zip というjarファイルをlibに登録することで手軽に行うことができるようになります。

動きとしてはJSPでファイルを選択してもらい、
サーブレットでWEB-INFのdataフォルダに保存するという処理になります。

1、JSPの作成
<%@ page contentType="text/html;charset=Windows-31J" %>
<html>
<head>
<title>ファイルのアップロード</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data"
action="UploadServlet">
ファイルパス:
<input type="file" name="fl" size="75" />
<input type="submit" value="アップロード" />
</form>
</body>
</html>

2、Servletの作成
package to.msn.wings.javatips;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request
, HttpServletResponse response)
throws ServletException, IOException {
String path=getServletContext().getRealPath("WEB-INF/data");
DiskFileUpload objDfu=new DiskFileUpload();
// アップロードファイルの最大サイズ(-1は無限)
objDfu.setSizeMax(-1);
// バッファサイズ
objDfu.setSizeThreshold(1024);
// 一時ファイルの保存先フォルダ
objDfu.setRepositoryPath(path);
// ヘッダの文字エンコーディング
objDfu.setHeaderEncoding("Windows-31J");
try {
// アップロードされたファイル情報を
// FileItemオブジェクトのリストとして取得
List objLst=objDfu.parseRequest(request);
Iterator objItr=objLst.iterator();
// リストから順にファイルデータを取り出し、
// 「/WEB-INF/data/元のファイル名」の形式で
// アップロードファイルを保存
while(objItr.hasNext()){
FileItem objFi=(FileItem)objItr.next();
if(!objFi.isFormField()){
// アップロードファイルの元ファイル名を取得
String strNam=objFi.getName();
if(strNam!=null && !strNam.equals("")){
strNam=(new File(strNam)).getName();
objFi.write(new File(path + "/" + strNam));
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 処理後は元のupload.jspにリダイレクト
response.sendRedirect("upload.jsp");
}

JSP(データベースPostgreSQ)サンプル

<%@ page contentType="text/html; charset=Shift_JIS" %>
<%@ page import="java.sql.*" %>
<%
Connection con = null;
Statement stmt = null;
try {
// ドライバクラスをロード
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("org.postgresql.Driver"); // PostgreSQLの場合

// データベースへ接続
//String url = "jdbc:mysql:///hellodb?useUnicode=true&characterEncoding=SJIS";
con =
DriverManager.getConnection("jdbc:postgresql:db001",
"postgres",
"zxcvvcxz"); // PostgreSQLの場合

//con = DriverManager.getConnection(url);
// ステートメントオブジェクトを生成
stmt = con.createStatement();
// 全ての行を検索するSQL文を作成
String sql = "SELECT * FROM tbl001";
// クエリーを実行して結果セットを取得
ResultSet rs = stmt.executeQuery(sql);


session.setAttribute("AAAA","FF");
%>
<html>
<head>
<title>JSPでDB接続</title>
</head>
<body>
<table border="1">
<tr>
<th>NO</th>
<th>言語</th>
<th>メッセージ</th>
</tr>
<%
// 検索された行数分ループ
while(rs.next()){
%>
<tr>
<td><%=rs.getInt("rid") %></td>
<td><%=rs.getString("username") %></td>
<td><%=rs.getString("username") %></td>
</tr>
<%
} // end while
%>
</table>
</body>
</html>
<%
} catch (Exception e) {
out.println("<font color=red><h3>エラー!</h3></font>" + e);
e.printStackTrace();
} finally {
// データベースへの接続をクローズします
try {
if (stmt!=null) {
stmt.close();
}
if (con!=null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
%>