Java web画像アップロード(ファイルアップロード)

10972 ワード

1、まずレイアウト画面index.jsp
"java" import="java.util.*" pageEncoding="utf-8"%>
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="">

    <title>My JSP 'index.jsp' starting pagetitle>
    <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="uploadpic" enctype="multipart/form-data" method="post">
     <input type="file" name="file1">
     <input type="submit" value="  ">
  form>
  body>
html>

2、提出フォームに対応するservlet(PicUpload.java)を作成し、画像をプロジェクトに対応するuploadファイルにアップロードし、画像がプロジェクトのあるディスクにアップロードされたかどうかを確認する.
package com.upload;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.beans.Pic;
public class PicUpload extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("nihao");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //           
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //         
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //     
        // sfu.setSizeMax(1024 * 400);
        //                  FileItem   
        try {
            List items = sfu.parseRequest(req);
            //      
            for (int i = 0; i < items.size(); i++) {
                System.out.println("01");
                FileItem item = items.get(i);
                // isFormField true,            
                if (!item.isFormField()) {
                    ServletContext sctx = getServletContext();
                    //            
                    // upload                          
                    String path = sctx.getRealPath("");
                    System.out.println(path);
                    //      
                    String fileName = item.getName();
                    String lind = fileName.substring(fileName.lastIndexOf("."));
                    String picname =String.valueOf(System.currentTimeMillis())
                            + lind;
                    File file = new File(path +"\\"+"upload"+"\\"+picname);
                    System.out.println(picname);
                    if (!file.exists()) {
                        item.write(file);
                        //                

                        List allpic=picDao.getAllPic();
                        req.setAttribute("piclist", allpic);
                        req.setAttribute("name", "1443751877241.jpg");
                        RequestDispatcher dispatcher = req.getRequestDispatcher("ok.jsp"); //   req    RequestDispatcher  
                        dispatcher.forward(req, resp);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3、servlet(web.xml)の構成
<servlet>
      <servlet-name>Uploadpicservlet-name>
      <servlet-class>com.upload.PicUploadservlet-class>
servlet>
<servlet-mapping>
      <servlet-name>Uploadpicservlet-name>
      <url-pattern>/uploadpicurl-pattern>
servlet-mapping>

4、注意事項アップロード画像はfile uploadコンポーネントを使用しており、対応するjarパッケージjarパッケージダウンロードアドレスclick hereを追加する必要がある.