13 springmvc完成文件上传

本节操作完成了springmvc下的文件上传。

1、环境约束

  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64
  • spring 3.2.18

2、前提约束

3、修改springmvc.xml

    <!--==================================文件上传 start ======================================-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="1024000"></property>
    </bean>
    <!--===============文件上传 end【注意:这里上传文件约束大小最大为1024字节】===================-->

4、在java文件夹下创建net.wanho.controller.FileUploadController.java

package net.wanho.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class FileUploadController {

    final String FILE_DEST_DIR = "D:/";

    @RequestMapping("/testFileUpload")
    @ResponseBody
    public String testFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String filePath = FILE_DEST_DIR + file.getOriginalFilename();
        file.transferTo(new File(filePath));
        return "success";
    }
}

5、在webapp文件夹下创建index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="testFileUpload" method="POST" enctype="multipart/form-data">
    File: <input type="file" name="file"/>
    <input type="submit" value="submit"/>
</form>

</body>
</html>

6、测试

打开浏览器,输入http://localhost:8088/fileupload.jsp,具体操作如下图所示:
测试文件上传
此时,在D盘下就有了刚才上传的文件。【注意:因为当前的机子既是测试机,也是服务器,待上传的文件以及上传之后的文件都在这台机子,请不要混淆。】
至此,我们完成了springmvc中文件的上传操作并进行了测试。

猜你喜欢

转载自www.cnblogs.com/alichengxuyuan/p/12554663.html
13
13)
今日推荐