ファイルアップロードのSerlvetクラス
2196 ワード
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload upload;
private final long MAXSize = 4194304*2L;//4*2MB
private String filedir=null;
/**
* @see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
*
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
FileItemFactory factory = new DiskFileItemFactory();// Create a factory for disk-based file items
this.upload = new ServletFileUpload(factory);// Create a new file upload handler
this.upload.setSizeMax(this.MAXSize);// Set overall request size constraint 4194304
filedir=config.getServletContext().getRealPath("images");
System.out.println("filedir="+filedir);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
try {
List<FileItem> items = this.upload.parseRequest(request);
if(items!=null && !items.isEmpty()){
for (FileItem fileItem : items) {
String filename=fileItem.getName();
String filepath=filedir+File.separator+filename;
System.out.println(" :"+filepath);
File file=new File(filepath);
InputStream inputSteam=fileItem.getInputStream();
BufferedInputStream fis=new BufferedInputStream(inputSteam);
FileOutputStream fos=new FileOutputStream(file);
int f;
while((f=fis.read())!=-1)
{
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();
System.out.println(" :"+filename+" !");
}
}
System.out.println(" !");
out.write(" !");
} catch (FileUploadException e) {
e.printStackTrace();
out.write(" :"+e.getMessage());
}
}
}