Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > непонятки с файлом


Автор: Swatch 14.4.2008, 12:10
Добрый день.

Делаю сохранение файла в БД с помощью хибернейта. храню блоб, одновременно сохраняю на димк:
Код

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {
        ActionMessages errors = null;
        DynaActionForm df = (DynaActionForm)actionForm;
        FormFile file = (FormFile)df.get("file");
        String title = (String)df.get("title");
        Blob blob = Hibernate.createBlob(file.getInputStream());
        String extension = null;

        errors = new ActionMessages();

        if(title.equals("")) {
            errors.add("title",new ActionMessage("error.title.required"));
        }

        if(file.getFileName().equals("")) {
            errors.add("file",new ActionMessage("error.file.required"));
        }

        saveErrors(httpServletRequest,errors);

        for (int i=file.getFileName().length()-1;i>=0;i--){
            int c = file.getFileName().codePointAt(i);
            if (c == 46){
                extension = file.getFileName().substring(i, file.getFileName().length());
            }
        }
        byte[] f = new byte[(int) blob.length()];

       FileOutputStream fos = new  FileOutputStream(getCurrentDirectory() + "/" + title + extension);
       for(int i=0; i<f.length;i++ ){
            fos.write(f[i]);
       }
        if(errors.isEmpty()){
            doc doc = new doc();
            doc.setTitle(title);
            doc.setAttachment(blob);
            doc.setExtension(extension);
            HibernateUtil.Save(doc);
            return actionMapping.findForward("main");
        }else{
            return actionMapping.findForward("invalid");
        }
     }


После этого пытаюсь открыть сохраненный файл из БД:
Код

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception, ServletException {
        Long id = null;

        id = ((MainForm) actionForm).getId();
        doc doc = new doc();
        HibernateUtil.Load(doc, id);

        Blob blob = doc.getAttachment();
        File f = new File(getCurrentDirectory() + "/" +"attachement" + doc.getExtension());
        
        byte[] file = new byte[(int) blob.length()];

       FileOutputStream fos = new  FileOutputStream(f);
       for(int i=0; i<file.length;i++ ){
            fos.write(file[i]);
       }
        fos.close();
        String file_name = f.getCanonicalPath();         
        Runtime.getRuntime().exec("cmd /C " + "\"" + file_name + "\"");
        f.deleteOnExit();
        return (actionMapping.findForward("main"));
    }


Открываться, открывается, но внутри какая-то белиберда в виде квадратиков... причем так со всеми файлами.. их содержимое портиться или при сохранении, или при открытии... 

ошибку найти не получается... помогите, пожалуйста... Может кто-нибудь знает, в чем проблема и как с ней бороться?!

Автор: AlexeyVorotnikov 15.4.2008, 09:49
У вас в обоих случаях массивы байтов, которые пишутся на диск ничем не заполняются, потому на диск пишется всякий мусор.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)