美文网首页
springMVC05--实现文件上传

springMVC05--实现文件上传

作者: exmexm | 来源:发表于2017-08-31 19:19 被阅读0次

    主要通过common-fileupload来实现
    导入相关jar包common-fileupload、common-io
    配置SpringMVC的文件解析器:

    <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8" />
            <property name="maxUploadSize" value="100000" />
            <property name="maxInMemorySize" value="40960" />
        </bean>
    

    接着编写Controller:

    @Controller
    public class FileUploadController {
        @RequestMapping("/file")
        public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
            InputStream is = file.getInputStream();
            String path = request.getContextPath() + "/upload";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File toSave = new File(path, file.getOriginalFilename());
            OutputStream os = new FileOutputStream(toSave);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            is.close();
            System.out.println(toSave.getAbsolutePath());
            return "success";
        }
    }
    

    最后编写ui:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>上传文件</title>
    </head>
    <body>
        <h1>Please upload a file</h1>
        <%
            String path = request.getContextPath();
        %>
        <form method="post" action="<%=path%>/file.do"
            enctype="multipart/form-data">
            <input type="text" name="name" /> <input type="file" name="file" />
            <input type="submit" />
        </form>
    </body>
    </html>
    
    总结:

    终于学会好好地啾啾文档了。
    有啥问题多看看文档哈哈哈哈

    相关文章

      网友评论

          本文标题:springMVC05--实现文件上传

          本文链接:https://www.haomeiwen.com/subject/vxccjxtx.html