Java 类play.mvc.Http.MultipartFormData 实例源码

项目:rental-helper    文件:CreateProfile.java   
public Result submit() {
    User user = User.findByEmail(session().get("email"));
    Form<UserProfile> filledForm = profileForm.bindFromRequest();

    if (filledForm.hasErrors()) {
        return badRequest(createprofile.render(filledForm));
    } else {
        MultipartFormData body = request().body().asMultipartFormData();
        FilePart picture = body.getFile("image");
        UserProfile newProfile = filledForm.get();
        newProfile.image = picture.getFile();
        String filePath = "public/user_pictures/"+ user.email + ".png";
        newProfile.saveImage(picture.getFile(), filePath);
        newProfile.userId = user.id;
        newProfile.save();
        return ok(viewprofile.render(user, newProfile));
    }
}
项目:ObservaTerra42    文件:Application.java   
public static Result guardarArchivo() {
    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fichero = body.getFile("archivo");

    String nombreFichero = fichero.getFilename();
    int indice = nombreFichero.lastIndexOf(".");
    String type = nombreFichero.substring(indice + 1, nombreFichero.length());

    if(indice != -1)
        nombreFichero = nombreFichero.substring(0,indice);

    String tipo = fichero.getContentType();

    File file = fichero.getFile();
    File newFile = new File("public/data/" + nombreFichero + "."+ type);
    try {
        Files.copy(file, newFile);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return index();
}
项目:ObservaTerra42    文件:API.java   
public static Result uploadExcel() {
try {
  MultipartFormData body = request().body().asMultipartFormData();
  FilePart excel = body.getFile("excel");
  if (excel != null) {
        File file = excel.getFile();
        ExcelReader reader = new ExcelReader();
        List<Observation> obsList = reader.read(new FileInputStream(file));
        for (Observation obs: obsList) {
            obs.save();
        }
        Logger.info("Excel file uploaded with " + obsList.size() + " observations");
        return redirect(routes.Application.index());
   } else {
        Logger.error("Missing file to upload ");
        return redirect(routes.Application.index());    
   } 
  }
catch (IOException e) {
  return(badRequest(Messages.get("read.excel.error") + "." + e.getLocalizedMessage())); 
}
}
项目:aorra    文件:FileStoreController.java   
@SubjectPresent
public Result updateFile(final String fileID) {
  final MultipartFormData body = request().body().asMultipartFormData();
  if (body == null || body.getFiles().size() != 1) {
    if (request().headers().containsKey("Content-Type")) {
      if (request().body().asRaw() != null) {
        return updateToFile(fileID, request().body().asRaw().asBytes());
      } else if (request().body().asText() != null) {
        return updateToFile(fileID, request().body().asText().getBytes());
      }
    }
    return badRequest("Request must contain a single file to upload.")
        .as("text/plain");
  } else {
    return uploadToFile(fileID, body.getFiles().get(0));
  }
}
项目:aorra    文件:FileStoreController.java   
protected Result uploadToFile(final String fileID,
    final MultipartFormData.FilePart filePart) {
  return fileBasedResult(fileID, new FileOp() {
    @Override
    public final Result apply(Session session, FileStore.File f)
        throws RepositoryException, FileNotFoundException {
      try {
        final JsonBuilder jb = new JsonBuilder();
        f.update(getMimeType(filePart),
            new FileInputStream(filePart.getFile()));
        session.save();
        Logger.info(String.format(
          "file %s content type %s uploaded to %s by %s",
          filePart.getFilename(), getMimeType(filePart),
          f.getPath(), getUser()));
        return ok(jb.toJsonShallow(f)).as("application/json; charset=utf-8");
      } catch (ItemExistsException iee) {
        return forbidden(iee.getMessage());
      } catch (AccessDeniedException ade) {
        return forbidden(
            "Insufficient permissions to upload files to folder.");
      }
    }
  });
}
项目:aorra    文件:FileStoreController.java   
private FileStore.File updateFileContents(FileStore.Folder folder,
    MultipartFormData.FilePart filePart) throws RepositoryException {
  try {
    final FileStore.FileOrFolder fof =
        folder.getFileOrFolder(filePart.getFilename());
    final FileStore.File f;
    if (fof == null) {
      f = folder.createFile(filePart.getFilename(),
          getMimeType(filePart),
          new FileInputStream(filePart.getFile()));
    } else if (fof instanceof FileStore.File) {
      throw new ItemExistsException(
          "File already exists. Add a new version instead.");
    } else {
      throw new ItemExistsException("Item exists and is not a file.");
    }
    return f;
  } catch (FileNotFoundException e) {
    throw new RuntimeException(e);
  }
}
项目:w3act    文件:TargetController.java   
@Security.Authenticated(SecuredController.class)
public static Result uploadExcel() {
    MultipartFormData body = request().body().asMultipartFormData();
    FilePart picture = body.getFile("excelFile");
    if(picture != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType();
        File file = picture.getFile();
        Logger.info("Uploaded " + fileName);
        try {
            excelParser(file);
            flash("success", "File " + fileName + " uploaded");
        }
        catch(Throwable e) {
            flash("error", "File " + fileName + " parse errors:");
            flash("error_log", e.getMessage());
            e.printStackTrace();
        }
        return redirect(routes.TargetController.upload());
    }
    else {
        Logger.info("Upload failed ");
        flash("error", "Missing file");
        return redirect(routes.TargetController.upload());
    }
}
项目:exam    文件:AttachmentController.java   
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result addAttachmentToQuestion() {

    MultipartFormData<File> body = request().body().asMultipartFormData();
    FilePart<File> filePart = body.getFile("file");
    if (filePart == null) {
        return notFound();
    }
    File file = filePart.getFile();
    if (file.length() > AppUtil.getMaxFileSize()) {
        return forbidden("sitnet_file_too_large");
    }
    Map<String, String[]> m = body.asFormUrlEncoded();
    Long qid = Long.parseLong(m.get("questionId")[0]);
    Question question = Ebean.find(Question.class)
            .fetch("examSectionQuestions.examSection.exam.parent")
            .where()
            .idEq(qid)
            .findUnique();
    if (question == null) {
        return notFound();
    }
    String newFilePath;
    try {
        newFilePath = copyFile(file, "question", qid.toString());
    } catch (IOException e) {
        return internalServerError("sitnet_error_creating_attachment");
    }
    // Remove existing one if found
    removePrevious(question);

    Attachment attachment = createNew(filePart, newFilePath);

    question.setAttachment(attachment);
    question.save();

    return ok(attachment);
}
项目:exam    文件:AttachmentController.java   
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result addAttachmentToExam() {
    MultipartFormData<File> body = request().body().asMultipartFormData();
    FilePart<File> filePart = body.getFile("file");
    if (filePart == null) {
        return notFound();
    }
    File file = filePart.getFile();
    if (file.length() > AppUtil.getMaxFileSize()) {
        return forbidden("sitnet_file_too_large");
    }
    Map<String, String[]> m = body.asFormUrlEncoded();
    Long eid = Long.parseLong(m.get("examId")[0]);
    Exam exam = Ebean.find(Exam.class, eid);
    if (exam == null) {
        return notFound();
    }
    User user = getLoggedUser();
    if (!user.hasRole(Role.Name.ADMIN.toString(), getSession()) && !exam.isOwnedOrCreatedBy(user)) {
        return forbidden("sitnet_error_access_forbidden");
    }
    String newFilePath;
    try {
        newFilePath = copyFile(file, "exam", eid.toString());
    } catch (IOException e) {
        return internalServerError("sitnet_error_creating_attachment");
    }
    // Delete existing if exists
    removePrevious(exam);

    Attachment attachment = createNew(filePart, newFilePath);
    exam.setAttachment(attachment);
    exam.save();
    return ok(attachment);
}
项目:rental-helper    文件:EditProfile.java   
public Result submit() {
    User user = User.findByEmail(session().get("email"));
    Form<UserProfile> filledForm = profileForm.bindFromRequest();
    if (filledForm.hasErrors()) {
        return badRequest(editprofile.render(user, profileForm));
    } else {
        MultipartFormData body = request().body().asMultipartFormData();
        FilePart picture = null;
        if (body != null && body.getFile("image") != null) {
            picture = body.getFile("image");
        }
        UserProfile profile = null;
        if (user != null) {
            profile = UserProfile.findByUserId(user.id);
        } else {
            profile = UserProfile.findByUserId(filledForm.get().userId);
        }
        profile.set(filledForm.get());
        if (picture != null && picture.getFile() != null) {
            profile.image = picture.getFile();
            String filePath = "public/user_pictures/" + user.email + ".png";
            profile.saveImage(picture.getFile(), filePath);
        }
        profile.save();
        return GO_VIEW;
    }
}
项目:app-framework    文件:FileAttachmentHelper.java   
/**
 * Return true if the specified form contains a valid file field.
 * 
 * @param fieldName
 *            the field name
 * 
 * @return a boolean
 */
public static boolean hasFileField(String fieldName) {

    boolean r = false;

    MultipartFormData body = Controller.request().body().asMultipartFormData();
    if (body != null) {

        FileType fileType = getFileType(fieldName);
        String fileFieldName = getFileInputName(fieldName, fileType);

        switch (fileType) {
        case UPLOAD:
            if (body.getFile(fileFieldName) != null) {
                r = true;
            }
            break;
        case URL:
            if (body.asFormUrlEncoded().get(fileFieldName)[0] != null && !body.asFormUrlEncoded().get(fileFieldName)[0].equals("")) {
                r = true;
            }
            break;
        }
    }

    return r;
}
项目:app-framework    文件:FileAttachmentHelper.java   
/**
 * Get the file part of the attachment for UPLOAD type.
 * 
 * @param fieldName
 *            the field name
 */
public static FilePart getFilePart(String fieldName) {

    FileType fileType = getFileType(fieldName);

    if (fileType.equals(FileType.UPLOAD)) {
        MultipartFormData body = Controller.request().body().asMultipartFormData();
        FilePart filePart = body.getFile(getFileInputName(fieldName, fileType));
        return filePart;
    }

    return null;

}
项目:htwplus    文件:ProfileController.java   
/**
 * Handles the upload of the temporary avatar image
 *
 * @param id
 * @return
 */
public Result createTempAvatar(Long id) {

    Account account = accountManager.findById(id);

    if (account == null) {
        return notFound();
    }

    ObjectNode result = Json.newObject();
    MultipartFormData body = request().body().asMultipartFormData();

    if (body == null) {
        result.put("error", "No file attached");
        return badRequest(result);
    }

    MultipartFormData.FilePart avatar = body.getFile("avatarimage");

    if (avatar == null) {
        result.put("error", "No file with key 'avatarimage'");
        return badRequest(result);
    }

    try {
        avatarManager.setTempAvatar(avatar, account.id);
    } catch (ValidationException e) {
        result.put("error", e.getMessage());
        return badRequest(result);
    }

    result.put("success", getTempAvatar(id).toString());
    return ok(result);
}
项目:woc    文件:Application.java   
/**
 * Handles the file upload.
 * @throws OWLOntologyCreationException 
 * @throws InterruptedException 
 */
public static Result uploadFile() throws OWLOntologyCreationException, InterruptedException {

    Form<Ontology> ontologyForm = form(Ontology.class);

    MultipartFormData body = request().body().asMultipartFormData();
      FilePart ontologyFile = body.getFile("ontology");
      if (ontologyFile != null) {
       String fileName = ontologyFile.getFilename();
       String contentType = ontologyFile.getContentType(); 
       // ontology.get
       File file = ontologyFile.getFile();

       try{ 
           loadOntology(file.getPath());
       }
       catch(UnparsableOntologyException ex){
           return ok(index.render("Not a valid Ontology File"));
       }

      //Initiate the reasoner to classify ontology
      if (BeeOntologyfile.exists())
      {
        reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);

        //System.out.println("suppp");
        loadBeeCharacteristics();   
      }

      Ontology ontology = new Ontology(KeyDescriptionArraylist, null, null);
      return ok(view.render(ontology.features));

      } else {
        flash("error", "Missing file");
        return ok(index.render("File Not Found"));  
      }
}
项目:CS784-Data_Integration    文件:RuleController.java   
public static Result importFeatures(String name){
    DynamicForm form = form().bindFromRequest();
    Logger.info("PARAMETERS : " + form.data().toString());
    String table1Name = form.get("table1_name");
    String table2Name = form.get("table2_name");

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fp = body.getFile("csv_file_path");

    if (fp != null) {
        String fileName = fp.getFilename();
        String contentType = fp.getContentType();
        Logger.info("fileName: " + fileName + ", contentType: " + contentType);
        File file = fp.getFile();
        Project project = ProjectDao.open(name);

        try{
            Table table1 = TableDao.open(name, table1Name);
            Table table2 = TableDao.open(name, table2Name);
            List<Feature> features = RuleDao.importFeaturesFromCSVWithHeader(project,
                    table1, table2, file.getAbsolutePath());
            // save the features - this automatically updates and saves the project
            System.out.println(features);
            System.out.println(name);
            RuleDao.save(name, features);
            ProjectController.statusMessage = "Successfully imported " + features.size() + " features.";
        }
        catch(IOException ioe){
            flash("error", ioe.getMessage());
            ProjectController.statusMessage = "Error: " + ioe.getMessage();
        }
    } else {
        flash("error", "Missing file");
        ProjectController.statusMessage = "Error: Missing file";
    }
    return redirect(controllers.project.routes.ProjectController.showProject(name));
}
项目:CS784-Data_Integration    文件:RuleController.java   
public static Result importRules(String name){
    DynamicForm form = form().bindFromRequest();
    Logger.info("PARAMETERS : " + form.data().toString());
    String table1Name = form.get("table1_name");
    String table2Name = form.get("table2_name");

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fp = body.getFile("csv_file_path");

    if (fp != null) {
        String fileName = fp.getFilename();
        String contentType = fp.getContentType();
        Logger.info("fileName: " + fileName + ", contentType: " + contentType);
        File file = fp.getFile();
        Project project = ProjectDao.open(name);

        try{
            List<Rule> rules = RuleDao.importRulesFromCSVWithHeader(project,
                    table1Name, table2Name, file.getAbsolutePath());
            // save the features - this automatically updates and saves the project
            RuleDao.saveRules(name, rules);
            ProjectController.statusMessage = "Successfully imported " + rules.size() + " rules.";
        }
        catch(IOException ioe){
            flash("error", ioe.getMessage());
            ProjectController.statusMessage = "Error: " + ioe.getMessage();
        }
    } else {
        flash("error", "Missing file");
        ProjectController.statusMessage = "Error: Missing file";
    }
    return redirect(controllers.project.routes.ProjectController.showProject(name));
}
项目:CS784-Data_Integration    文件:RuleController.java   
public static Result importMatchers(String name){
    DynamicForm form = form().bindFromRequest();
    Logger.info("PARAMETERS : " + form.data().toString());
    String table1Name = form.get("table1_name");
    String table2Name = form.get("table2_name");

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fp = body.getFile("csv_file_path");

    if (fp != null) {
        String fileName = fp.getFilename();
        String contentType = fp.getContentType();
        Logger.info("fileName: " + fileName + ", contentType: " + contentType);
        File file = fp.getFile();
        Project project = ProjectDao.open(name);

        try{
            List<Matcher> matchers = RuleDao.importMatchersFromCSVWithHeader(project,
                    table1Name, table2Name, file.getAbsolutePath());
            // save the features - this automatically updates and saves the project
            RuleDao.saveMatchers(name, matchers);
            ProjectController.statusMessage = "Successfully imported " + matchers.size() + " matchers.";
        }
        catch(IOException ioe){
            flash("error", ioe.getMessage());
            ProjectController.statusMessage = "Error: " + ioe.getMessage();
        }
    } else {
        flash("error", "Missing file");
        ProjectController.statusMessage = "Error: Missing file";
    }
    return redirect(controllers.project.routes.ProjectController.showProject(name));
}
项目:geo-publisher    文件:Styles.java   
@BodyParser.Of (value = BodyParser.MultipartFormData.class, maxLength = 2 * 1024 * 1024)
public static Result handleFileUploadForm () {
    final MultipartFormData body = request ().body ().asMultipartFormData ();
    final FilePart uploadFile = body.getFile ("file");

    if (uploadFile == null) {
        return ok (uploadFileForm.render (null));
    }

    final String content = handleFileUpload (uploadFile.getFile ());

    return ok (uploadFileForm.render (content));
}
项目:ObservaTerra51    文件:Application.java   
public static Result uploadFile() {

    MultipartFormData part = request().body().asMultipartFormData();
    FilePart file = part.getFile("file");

    String filename = file.getFilename();
    String[] parts = filename.split(".");
    String name = parts[0];
    String ext;

    try {
        ext = parts[1];
    }
    catch (ArrayIndexOutOfBoundsException iobe) {
        ext = "-";
    }

    User user = User.findByUsername(session().get("login"));

    Document doc = new Document(file.getFile(), ext, user, name);

    user.documentos.add(doc);

    doc.save();
    user.save();

    return ok(profile.render(user));
}
项目:aorra    文件:FileStoreController.java   
@SubjectPresent
public Result uploadToFolder(final String folderID) {
  return folderBasedResult(folderID, new FolderOp() {
    @Override
    public final Result apply(Session session, FileStore.Folder folder)
        throws RepositoryException {
      final MultipartFormData body = request().body().asMultipartFormData();
      if (body == null || body.getFiles().size() != 1) {
        return badRequest("Request must contain a single file to upload.")
            .as("text/plain");
      }
      final MultipartFormData.FilePart filePart = body.getFiles().get(0);
      try {
        final JsonBuilder jb = new JsonBuilder();
        FileStore.File f = updateFileContents(folder, filePart);
        session.save();
        Logger.info(String.format(
          "file %s content type %s uploaded to %s by %s",
          filePart.getFilename(), getMimeType(filePart),
          f.getPath(), getUser()));
        return created(jb.toJsonShallow(f))
            .as("application/json; charset=utf-8");
      } catch (ItemExistsException iee) {
        return forbidden(iee.getMessage());
      } catch (AccessDeniedException ade) {
        return forbidden(
            "Insufficient permissions to upload files to folder.");
      }
    }
  });
}
项目:play2-casadocodigo    文件:FilmeCRUD.java   
public static Result upload() {

        MultipartFormData body = request().body().asMultipartFormData();
        FilePart picture = body.getFile("picture");
        String extensaoPadraoDeImagens = Play.application().configuration().getString("extensaoPadraoDeImagens");
        if (picture != null) {

            String filmeId = form().bindFromRequest().get("filmeId");
            String imagem = filmeId + extensaoPadraoDeImagens;
            String contentType = picture.getContentType();
            File file = picture.getFile();

            String diretorioDeImagens = Play.application().configuration().getString("diretorioDeImagens");
            String contentTypePadraoDeImagens = Play.application().configuration().getString("contentTypePadraoDeImagens");

            if (contentType.equals(contentTypePadraoDeImagens)) {

                file.renameTo(new File(diretorioDeImagens,imagem));
                return ok(views.html.upload.render("Arquivo  \"" + imagem + "\" do tipo [" + contentType + "] foi carregado com sucesso !"));

            } else {

                return ok(views.html.upload.render("Imagens apenas no formato \"" + contentTypePadraoDeImagens + "\" serão aceitas!"));

            }

        } else {
            flash("error","Erro ao fazer upload");
            return redirect(routes.Application.index());
        }
    }
项目:WorkshopManager    文件:WorkshopController.java   
/**
    * Upload the specified image and return the link to it
 * 
 * @return the image link in the system
 */
private static String uploadImage() {
    String imageLocation    =   Play.application().configuration().getString("workshop.images.url") + File.separator;
    String defaultImage     =   imageLocation + "default.png";

        MultipartFormData body = request().body().asMultipartFormData();
        FilePart picture = body != null ? body.getFile("image") : null;
        if (picture != null) {
            String fileName = picture.getFilename();
            File file = picture.getFile();

           // We save the file
        String myUploadPath = Play.application().path()
                + File.separator
                + Play.application().configuration().getString("workshop.images.directory");

        // We check if the dest file exists
        File dest = new File(myUploadPath, fileName); 
        if ( dest.exists() ) {
            dest.delete();
        }

        // If the file copy encounter an exception, we use the default picture
        if ( FilesUtils.fastCopyFileCore( file, dest ) ) {
            return imageLocation + fileName;
        }
        }

        return defaultImage;
   }
项目:WorkshopManager    文件:WorkshopController.java   
/**
 * Upload the specified File and return the link to it
 * 
 * @return the File link in the system
 */
private static String uploadRessources( Workshop workshop ) {
    SimpleDateFormat    simpleDateFormat    =   new SimpleDateFormat("[yyyy-MM]");
    String              destFolderName      =   simpleDateFormat.format( workshop.workshopSession.get(0).nextPlay ) + " - " + workshop.subject;
    String              ressourceLocation   =   Play.application().configuration().getString("workshop.ressources.url") + File.separator + destFolderName + File.separator;

        MultipartFormData   body                =   request().body().asMultipartFormData();
        FilePart            ressource           =   body != null ? body.getFile("workshopSupportFile") : null;

        if (ressource != null && !StringUtils.EMPTY.equals( ressource.getFilename()) ) {
            String          fileName            =   ressource.getFilename();
            File            file                =   ressource.getFile();

            // We save the file
        String          myUploadPath        =   Play.application().path() + File.separator
                                                    + Play.application().configuration().getString("workshop.ressources.directory")
                                                    + File.separator + destFolderName;
        File            destFolder          =   new File(myUploadPath);
        destFolder.mkdirs();

        // We check if the dest file exists
        File dest = new File(myUploadPath, fileName); 
        if ( dest.exists() ) {
            dest.delete();
        }

        // If the file copy encounter an exception, we use the default picture
        if ( FilesUtils.fastCopyFileCore( file, dest ) ) {
            return ressourceLocation + fileName;
        }
        }

        return null;
   }
项目:maf-desktop-app    文件:SharedStorageManagerController.java   
/**
 * Upload a new file into the shared storage.
 * 
 * @param isInput
 *            if true the field name containing the file uploaded is
 *            IFrameworkConstants.INPUT_FOLDER_NAME
 *            (IFrameworkConstants.OUTPUT_FOLDER_NAME otherwise)
 * @return
 */
@BodyParser.Of(value = BodyParser.MultipartFormData.class, maxLength = MAX_FILE_SIZE)
public Promise<Result> upload(final boolean isInput) {
    final String folderName = isInput ? IFrameworkConstants.INPUT_FOLDER_NAME : IFrameworkConstants.OUTPUT_FOLDER_NAME;
    final

    // Test if the max number of files is not exceeded
    String[] files;
    try {
        files = getSharedStorageService().getFileList("/" + folderName);
    } catch (IOException e1) {
        return redirectToIndexAsPromiseWithErrorMessage(null);
    }
    int numberOfFiles = files != null ? files.length : 0;
    if (numberOfFiles >= getConfiguration().getInt("maf.sftp.store.maxfilenumber")) {
        return redirectToIndexAsPromiseWithErrorMessage(Msg.get("admin.shared_storage.upload.error.max_number"));
    }

    // Perform the upload
    return Promise.promise(new Function0<Result>() {
        @Override
        public Result apply() throws Throwable {
            try {
                MultipartFormData body = request().body().asMultipartFormData();
                FilePart filePart = body.getFile(folderName);
                if (filePart != null) {
                    IOUtils.copy(new FileInputStream(filePart.getFile()),
                            getSharedStorageService().writeFile("/" + folderName + "/" + filePart.getFilename(), true));
                    Utilities.sendSuccessFlashMessage(Msg.get("form.input.file_field.success"));
                } else {
                    Utilities.sendErrorFlashMessage(Msg.get("form.input.file_field.no_file"));
                }
            } catch (Exception e) {
                Utilities
                        .sendErrorFlashMessage(Msg.get("admin.shared_storage.upload.file.size.invalid", FileUtils.byteCountToDisplaySize(MAX_FILE_SIZE)));
                String message = String.format("Failure while uploading a new file in %s", folderName);
                log.error(message);
                throw new IOException(message, e);
            }
            return redirect(routes.SharedStorageManagerController.index());
        }
    });
}
项目:CS784-Data_Integration    文件:ProjectController.java   
public static Result importTableFromCSV(String projectName) {
    DynamicForm form = form().bindFromRequest();
    Logger.info("PARAMETERS : " + form.data().toString());
    String tableName = form.get("table_name");

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fp = body.getFile("csv_file_path");

    if (fp != null) {
        String fileName = fp.getFilename();
        String contentType = fp.getContentType();
        Logger.info("fileName: " + fileName + ", contentType: " + contentType);
        File file = fp.getFile();
        Set<DefaultType> defaultTypes = new HashSet<DefaultType>();
        boolean saveToDisk = false;
        if(null != form.get("table1_default")){
            defaultTypes.add(DefaultType.TABLE1);
        }
        if(null != form.get("table2_default")){
            defaultTypes.add(DefaultType.TABLE2);
        }
        if(null != form.get("candset_default")){
            defaultTypes.add(DefaultType.CAND_SET);
        }
        if(null != form.get("matches_default")){
            defaultTypes.add(DefaultType.MATCHES);
        }
        if(null != form.get("gold_default")){
            defaultTypes.add(DefaultType.GOLD);
        }
        if(null != form.get("save_to_disk")){
            saveToDisk = true;
        }
        try{
            Table table = TableDao.importFromCSVWithHeader(projectName, tableName,
                    file.getAbsolutePath());

            // save the table - this automatically updates the project but does not save it
            TableDao.save(table, defaultTypes, saveToDisk);
            statusMessage = "Successfully imported Table " + tableName + " with " + table.getSize() +
                    " tuples.";
        }
        catch(IOException ioe){
            flash("error", ioe.getMessage());
            statusMessage = "Error: " + ioe.getMessage();
        }
    } else {
        flash("error", "Missing file");
        statusMessage = "Error: Missing file";
    }
    return redirect(controllers.project.routes.ProjectController.showProject(projectName));
}
项目:CS784-Data_Integration    文件:ProjectController.java   
public static Result importTable(String projectName) {
    DynamicForm form = form().bindFromRequest();
    Logger.info("PARAMETERS : " + form.data().toString());
    String tableName = form.get("table_name");

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fp = body.getFile("table_file_path");

    if (fp != null) {
        String fileName = fp.getFilename();
        String contentType = fp.getContentType();
        Logger.info("fileName: " + fileName + ", contentType: " + contentType);
        File file = fp.getFile();
        Set<DefaultType> defaultTypes = new HashSet<DefaultType>();
        boolean saveToDisk = false;
        if(null != form.get("table1_default")){
            defaultTypes.add(DefaultType.TABLE1);
        }
        if(null != form.get("table2_default")){
            defaultTypes.add(DefaultType.TABLE2);
        }
        if(null != form.get("candset_default")){
            defaultTypes.add(DefaultType.CAND_SET);
        }
        if(null != form.get("matches_default")){
            defaultTypes.add(DefaultType.MATCHES);
        }
        if(null != form.get("gold_default")){
            defaultTypes.add(DefaultType.GOLD);
        }
        if(null != form.get("save_to_disk")){
            saveToDisk = true;
        }
        try{
            Table table = TableDao.importTable(projectName, tableName,
                    file.getAbsolutePath());

            // save the table - this automatically updates the project but does not save it
            TableDao.save(table, defaultTypes, saveToDisk);
            statusMessage = "Successfully imported Table " + tableName + " with " + table.getSize() +
                    " tuples.";
        }
        catch(IOException ioe){
            flash("error", ioe.getMessage());
            statusMessage = "Error: " + ioe.getMessage();
        }
    } else {
        flash("error", "Missing file");
        statusMessage = "Error: Missing file";
    }
    return redirect(controllers.project.routes.ProjectController.showProject(projectName));
}
项目:aorra    文件:FileStoreController.java   
protected String getMimeType(MultipartFormData.FilePart filePart) {
  return getMimeType(filePart.getFilename(), filePart.getContentType());
}
项目:app-framework    文件:FileAttachmentHelper.java   
/**
 * Get the URL of the attachment for URL type.
 * 
 * @param fieldName
 *            the field name
 */
public static String getUrl(String fieldName) {

    FileType fileType = getFileType(fieldName);

    if (fileType.equals(FileType.URL)) {
        MultipartFormData body = Controller.request().body().asMultipartFormData();
        return body.asFormUrlEncoded().get(getFileInputName(fieldName, fileType))[0];
    }

    return null;

}
项目:app-framework    文件:FileAttachmentHelper.java   
/**
 * Get the file type.
 * 
 * @param fieldName
 *            the field name
 */
public static FileType getFileType(String fieldName) {
    MultipartFormData body = Controller.request().body().asMultipartFormData();
    String fileType = body.asFormUrlEncoded().get(getFileTypeInputName(fieldName))[0];
    return FileType.valueOf(fileType);
}