Java загрузка файла в бд

195
20 апреля 2018, 17:03

Нужно загрузить .docx в MySQL, который скрыто создается по пути "D:/". Проблема в том что ранее созданный файл пересоздается пустым.

@RequestMapping(value = "/documents/add", method = RequestMethod.POST)
public String addDocument(Model model, @ModelAttribute("document") Document document,
                          @ModelAttribute("userForm") User userForm,@RequestParam("file") CommonsMultipartFile file)
                            throws IOException, Docx4JException {
        model.addAttribute("document", new Document());
        model.addAttribute("listDocuments", this.documentService.listDocuments());

        Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
        file = document.getFile();
        document.setAuthor(loggedInUser.getName());
        document.setCreated(Date.date());
        DocCreator.create(document.getName()); // создается .docx файл с текстом внутри
        Path path = Paths.get("D:/" + document.getName() + ".docx");
        file.transferTo(new File(path.toString())); //тут ранее созданный файл пересоздается, но уже пустой
        document.setFile(file);
        this.documentService.addDocument(document);
    return "redirect:/documents";
}

Модель Документа

@Entity
@Table(name = "documents")
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "created")
private String created;
@Column(name = "author")
private String author;
@Column(name = "description")
private String description;
@Transient
@Column(name = "file")
private CommonsMultipartFile file;
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCreated() {
    return created;
}
public void setCreated(String created) {
    this.created = created;
}
public String getAuthor() {
    return author;
}
public void setAuthor(String author) {
    this.author = author;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public CommonsMultipartFile getFile() {
    return file;
}
public void setFile(CommonsMultipartFile file) {
    this.file = file;
}

Реализация DAO

@Repository
public class DocumentDAOImpl implements DocumentDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public void addDocument(Document document) {
    Session session = this.sessionFactory.openSession();
    session.beginTransaction();
    session.persist(document);
    session.getTransaction().commit();
    session.close();
}

Jsp страница

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib prefix="from" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false" %>
<html>
<head>
<title>Documents Page</title>
<style type="text/css">
    .tg {
        border-collapse: collapse;
        border-spacing: 0;
        border-color: #ccc;
    }
    .tg td {
        font-family: Arial, sans-serif;
        font-size: 14px;
        padding: 10px 5px;
        border-style: solid;
        border-width: 1px;
        overflow: hidden;
        word-break: normal;
        border-color: #ccc;
        color: #333;
        background-color: #fff;
    }
    .tg th {
        font-family: Arial, sans-serif;
        font-size: 14px;
        font-weight: normal;
        padding: 10px 5px;
        border-style: solid;
        border-width: 1px;
        overflow: hidden;
        word-break: normal;
        border-color: #ccc;
        color: #333;
        background-color: #f0f0f0;
    }
    .tg .tg-4eph {
        background-color: #f9f9f9
    }
</style>
</head>
<body>
<c:if test="${pageContext.request.userPrincipal.name != null}">
<form id="logoutForm" method="POST" action="${contextPath}/logout">
    <input type="hidden" name="${_csrf.parameterName}" 
 value="${_csrf.token}"/>
</form>
<h2>Welcome ${pageContext.request.userPrincipal.name} | <a 
onclick="document.forms['logoutForm'].submit()">Logout</a>
</h2>
</c:if>
<br/>
<br/>
<h1>Document list</h1>
<c:if test="${!empty listDocuments}">
<table class="tg">
    <tr>
        <th width="80">ID</th>
        <th width="120">Name</th>
        <th width="120">Created</th>
        <th width="120">Author</th>
        <th width="120">Description</th>
        <th width="120">File</th>
        <th width="60">Edit</th>
        <th width="60">Delete</th>
    </tr>
    <c:forEach items="${listDocuments}" var="document">
        <tr>
            <td>${document.id}</td>
            <td>${document.name}</td>
            <td>${document.created}</td>
            <td>${document.author}</td>
            <td>${document.description}</td>
            <td>${document.file}</td>
            <td><a href="<c:url value='/download/${document.id}'/>">Download</a></td>
            <td><a href="<c:url value='/remove/${document.id}'/>">Delete</a></td>
        </tr>
    </c:forEach>
</table>
</c:if>

<h1>Add a Document</h1>
<c:url var="addAction" value="/documents/add"/>
<form:form action="${addAction}?${_csrf.parameterName}=${_csrf.token}"
       commandName="document" id="fileupload" method="post" enctype="multipart/form-data">
<input hidden type="file" name="file" id="file" >
<table>
    <tr>
        <td>
            <form:label path="name">
                <spring:message text="Name"/>
            </form:label>
        </td>
        <td>
            <form:input path="name"/>
        </td>
    </tr>
    <tr>
        <td>
            <form:label path="description">
                <spring:message text="Description"/>
            </form:label>
        </td>
        <td>
            <form:input path="description"/>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <c:if test="${!empty document.name}">
                <input type="submit"
                       value="<spring:message text="Edit Document"/> "/>
            </c:if>
            <c:if test="${empty document.name}">
                <input type="submit" value="<spring:message text="Add Document"/>" />
            </c:if>
        </td>
    </tr>
</table>
</form:form>
</body>
</html>

Table: documents

CREATE TABLE documents (
id          INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
name        VARCHAR(255) NOT NULL ,
created        DATE NOT NULL ,
author      VARCHAR(255) NOT NULL ,
description VARCHAR(255) NOT NULL ,
file        BLOB NOT NULL
)
ENGINE = MyISAM;
READ ALSO
Как добавить компонент в Pentaho CDE?

Как добавить компонент в Pentaho CDE?

Установлена Pentaho CE v8

199
Загрузка нескольких настроек логгера

Загрузка нескольких настроек логгера

В программе есть несколько слабо пересекающихся модулейХотелось для каждого модуля сделать свой конфигурационный файл логгера

135
Как вывести число прописью?

Как вывести число прописью?

Есть некое число(1<= n < 100)

146