【问题标题】:how do I read the file data and upload it?如何读取文件数据并上传?
【发布时间】:2018-04-03 06:49:50
【问题描述】:

我正在使用 Spring(4) MVC 和 Hibernate(4) 在 Eclipse 中创建一个动态 Web 项目,我想将文件的数据(文件将包含大量电话号码)上传到 mysql 中的表中,所以如何读取文件数据并上传?

【问题讨论】:

  • 您可以在您的 UI 中添加一个<input type="file"> 并将其作为多部分类型数据在控制器中使用,并将其作为字节数组(可能是 BLOB)存储在数据库中
  • @TinoMThomas 感谢您的及时回复,我也想知道如何将这个文件保存在 POJO 类中,然后使用 Hibernate 上传数据?
  • 请在提问前阅读this 部分,以便 SO 社区更好地了解您的问题。

标签: java hibernate spring-mvc


【解决方案1】:

你可以在Spring MVC中使用org.springframework.web.multipart.MultipartFile来上传文件

在控制器中添加方法

@RequestMapping(value = "/processUpload", method = RequestMethod.POST)
    public @ResponseBody RateResponse<String> processContractUpload(@RequestParam("txtFile") MultipartFile uploadedFile) throws IOException, InterruptedException{
        String result = "failure";
        String outFile = "C:\\temp\file.txt"
        if(file != null && file.getSize()>0){
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = null;
            try{
                stream = new BufferedOutputStream(new FileOutputStream(outFile));
                stream.write(bytes);
                result = "success";
            }finally {
                if(stream!=null){
                    stream.close(); 
                }
            }

        }

        return result;
    }

HTML 表单

<form id="uploadContractForm" name="uploadContractForm" action="processUpload" method="POST" enctype="multipart/form-data">        

<table class="tableStyle">
    <tr>

        <td><input type="file" name="txtFile" id="txtFile" style="background:white;" class="summaryTextSpan4"/></td>
        <td>&nbsp;</td>
        <td><input id="processbtn" type="button"  class="btn" value='Submit' /></td>
        <td><input id="refreshBtn" class="btn" type="button"  value='Reset' /></td>
    </tr>
</table>

启用 Spring Multipart 所需的 Spring bean 配置

<!-- File Upload Configuration Bean Details  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="maxUploadSize" value="1000000000" /> 
    </bean>

对于文件上传到数据库示例,您可以read here
也可以在 github 上from here 下载工作示例

【讨论】:

  • 非常感谢@Sushil,我几乎只这样做了,但我想使用休眠将此文件数据保存到 MySQL 中的表中,而不是将其保存在驱动器上。
  • 您要上传什么类型的文件数据。您可以使用 BufferedReader 从磁盘读取文件并转换为 java 对象。然后可以使用 DAO 将其存储到 DB... BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileLocation),Charset.forName("UTF-8")));
  • 我已经用工作示例代码链接更新了我的答案。希望能解决您的问题。 github.com/sushilsingh94/Spring-Examples/tree/master/…
  • 明白了!谢谢@Sushil
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2018-03-28
    相关资源
    最近更新 更多