示例#1
0
  public void upload() throws Exception {
    boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
    if (!isMultipart) {
      this.state = this.errorInfo.get("NOFILE");
      return;
    }

    if (this.inputStream == null) {
      this.state = this.errorInfo.get("FILE");
      return;
    }

    // 存储title
    this.title = this.getParameter("pictitle");

    try {
      String savePath = this.getFolder(this.savePath);

      if (!this.checkFileType(this.originalName)) {
        this.state = this.errorInfo.get("TYPE");
        return;
      }

      this.fileName = this.getName(this.originalName);
      this.type = this.getFileExt(this.fileName);
      this.url = savePath + "/" + this.fileName;

      FileOutputStream fos = new FileOutputStream(this.getPhysicalPath(this.url));
      BufferedInputStream bis = new BufferedInputStream(this.inputStream);
      byte[] buff = new byte[128];
      int count = -1;

      while ((count = bis.read(buff)) != -1) {

        fos.write(buff, 0, count);
      }

      bis.close();
      fos.close();

      this.state = this.errorInfo.get("SUCCESS");
    } catch (Exception e) {
      e.printStackTrace();
      this.state = this.errorInfo.get("IO");
    }
  }
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String id_book = "", len = "";

    // Imposto il content type della risposta e prendo l'output
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    // La dimensione massima di ogni singolo file su system
    int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
    // Dimensione massima della request
    int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB
    // Cartella temporanea
    File cartellaTemporanea = new File("C:\\tempo");

    try {
      // Creo un factory per l'accesso al filesystem
      DiskFileItemFactory factory = new DiskFileItemFactory();

      // Setto la dimensione massima di ogni file, opzionale
      factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);
      // Setto la cartella temporanea, Opzionale
      factory.setRepository(cartellaTemporanea);

      // Istanzio la classe per l'upload
      ServletFileUpload upload = new ServletFileUpload(factory);

      // Setto la dimensione massima della request, opzionale
      upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

      // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
      // tutti i field sia di tipo file che gli altri
      List<FileItem> items = upload.parseRequest(request);

      /*
       *
       * Giro per tutti i campi inviati
       */
      for (int i = 0; i < items.size(); i++) {
        FileItem item = items.get(i);

        // Controllo se si tratta di un campo di input normale
        if (item.isFormField()) {
          // Prendo solo il nome e il valore
          String name = item.getFieldName();
          String value = item.getString();
          if (name.equals("id_book")) {
            id_book = value;
          }
          if (name.equals("len")) {
            len = value;
          }
        }
        // Se si stratta invece di un file ho varie possibilità
        else {
          // Dopo aver ripreso tutti i dati disponibili
          String fieldName = item.getFieldName();
          String fileName = item.getName();
          String contentType = item.getContentType();
          boolean isInMemory = item.isInMemory();
          long sizeInBytes = item.getSize();

          // scrivo direttamente su filesystem

          File uploadedFile =
              new File("/Users/Babol/Desktop/dVruhero/aMuseWebsite/web/userPhoto/" + fileName);
          // Solo se veramente ho inviato qualcosa
          if (item.getSize() > 0) {
            item.write(uploadedFile);
            DBconnection.EditCoverBook(fileName, Integer.parseInt(id_book));
          }
        }
      }

      // out.println("</body>");
      // out.println("</html>");

    } catch (Exception ex) {
      System.out.println("Errore: " + ex.getMessage());
    } finally {
      if (len.equals("ita")) response.sendRedirect("modify_book.jsp?id_book=" + id_book);
      else response.sendRedirect("modify_book_eng.jsp?id_book=" + id_book);
    }
  }