SSM框架图片本地上传到服务器(前端如何通过form表单传递,springMVC如何接收以及存储,存储后的有效访问)

文件结构

在这里插入图片描述

1.目的和错误描述:

目的:

实现controller层中HelloController接收前端form表单提交的图片文件,把图片存储到webapp/static/headImg里面。

出现的问题:

存储之后如果需要调用这个图片,服务器会报404错误(该路径不存在)然而当我重启服务器后,调用该图片又能成功显示了

原因:

首先,我们代码中的路径都是根据服务器的文件目录来寻找文件的。我虽然把图片成功存储在webapp/static/headImg里面,但是整个过程中tomcat服务器一直在运行,不会把刚刚保存的图片加载到服务器的文件目录中,所以前端报404错误(该路径不存在)。当我从新启动服务器,服务器会进行初始化把刚刚下载的图片加载到服务器文件目录中,从而前端就能成功访问了。target文件就是服务器的文件目录,刚开始保存在webapp/static/headImg里的图片,只有加载到target/spring03/static/headImg里面才能被访问到。

解决方法:

在开始的时候就把图片保存到服务器文件目录中,这样就能直接访问该文件了。

解决问题时的曲折:

1.想过直接保存在本地C盘下面,通过绝对路径来访问,但是浏览器因为安全问题不支持直接通过绝对路径读取本地文件,报404错误。这个方法就失败了。然而并没有放弃,我通过网上说的修改一下Tomcat的serve.xml文件,加入这一句<Context path="upload" docBase="C:\workspace\project\upload\" debug="0" privileged="true"/>其中path代表虚拟的路径,doccBase代表绝对路径。访问文件时路径就是 /upload/文件名,然而一点用也没有,依然是404错误。这个还要该配置,还是换个方法吧。

2.想把文件保存到webapp/static/headImg里面直接访问,但是会404错误,我就想这把文件保存到webapp/static/headImg里面的同时,再保存一份到target/spring03/static/headImg里面,也就是服务器文件目录,就可以直接访问了,但是会出现文件流使用冲突,因为一个文件流只能输入到一个文件里面,再保存一份到target/spring03/static/headImg里面时就会报错。我进行了文件的复制还是行不通,后来反应过来,直接把文件保存到服务器目录文件中target/spring03/static/headImg,不就可以了。其实我是怕关闭服务器后文件没有了,但是我试过了,重启服务器文件不会消失。

2.实现代码:

前台jsp文件的form表单:
注意:form标签中一定要加enctype="multipart/form-data",不然controller层无法接收。

<form class="form-horizontal" action="${pageContext.request.contextPath}/empInsert" method="post" enctype="multipart/form-data" onsubmit="return validate()">
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="example-hf-ID">员工编号</label>
                            <div class="col-md-7">
                                <input type="text" class="form-control"  id="example-hf-ID" name="empID" placeholder="请输入员工编号..">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="example-hf-name">姓名</label>
                            <div class="col-md-7">
                                <input type="text" class="form-control"  id="example-hf-name" name="empName" placeholder="请输入姓名..">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-md-3 control-label" for="example-hf-password">性别</label>
                            <div class="example-box">
                                <label class="lyear-radio radio-inline radio-primary" style="margin-left: 20px">
                                    <input type="radio" name="sex" checked="checked" id='sexMan' value="1"><span></span><input>
                                </label>
                                <label class="lyear-radio radio-inline radio-primary">
                                    <input type="radio" name="sex" id='sexWoman' value="0"><span></span><input>
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="example-hf-password">工资</label>
                            <div class="col-md-7">
                                <input type="text" class="form-control"  id="example-hf-address" name="empSalary" placeholder="请输入工资..">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="example-hf-password">部门ID</label>
                            <div class="col-md-7">
                                <input type="text" class="form-control"  id="example-hf-birth" name="deptID" placeholder="请输入部门ID..">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="example-hf-password">上传员工照片</label>
                            <div class="col-md-7">
                                <input type="file" class="form-control"  id="example-hf-xueyuan" name="empImage" placeholder="请上传员工照片">
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-9 col-md-offset-3">
                                <button class="btn btn-primary btn-exit">取消</button>
                                <input type="submit" class="btn btn-primary btn-save" value="保存"></input>
                            </div>
                        </div>
                    </form>

后台controller层接收参数代码
MultipartFile empImage是用来接收file文件的
empImage.getOriginalFilename()获取上传的文件名字
empImage.transferTo(file2)文件的上传

//    新建
    @RequestMapping(value ="/empInsert", method = RequestMethod.POST)
    public ModelAndView empInsert(String empID , String empName, String sex, String empSalary, String deptID, MultipartFile empImage, HttpSession session) throws IOException {

        //获取文件原始名称
        String originalFilename = empImage.getOriginalFilename();
//        System.out.println(originalFilename+empName);
        //上传图片
//        if (empImage != null && originalFilename != null && originalFilename.length() > 0) {

            // 获得服务器/images文件路径,将来图片就存储在服务器的/images
            String realPath = session.getServletContext().getRealPath("/")+"static/headImg";
        String url = session.getServletContext().getRealPath("/");
        url=url.substring(0,url.indexOf("target"));
        url=url+ "src\\main\\webapp\\static\\headImg";
        System.out.println(realPath);
            File parent1 = new File(url);
            File parent2 = new File(realPath);
//            if (!parent1.exists()) {
//
//                parent1.mkdirs();
//
//            }
            System.out.println("服务器路径: parent = " + parent1);
            System.out.println("服务器路径: parent = " + parent2);
            // 获得文件后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            long millis = System.currentTimeMillis();


            // 组装文件名
            String fileName = millis + substring;
            System.out.println("最终文件名: fileName = " + fileName);
//            File file1 = new File(parent1, fileName);
            File file2 = new File(parent2, fileName);
        if (!file2.exists()){
            file2.mkdir();
        }
            // 执行上传
            try {
                empImage.transferTo(file2);

                int row = empService.empInsert(empID,empName, sex, empSalary, deptID, fileName);
                System.out.println("上传成功");
                if (row!=0){

                }
            } catch (IOException e) {
                System.out.println("上传");
                e.printStackTrace();
            }

//        }
       return new ModelAndView("redirect:/information?dept=allDept&empID="+empID);

    }

正常显示

在这里插入图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
首先,需要在前端页面设置一个文件上传的表单,可以使用HTML的input标签来实现: ```html <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" multiple="multiple"/> <input type="submit" value="上传"/> </form> ``` 其,`enctype="multipart/form-data"`表示使用多媒体表单进行数据提交,`input`标签的`name`属性必须为`file`,`multiple="multiple"`表示可以一次上传多个文件。 然后,在后台的Controller添加对应的处理方法: ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(HttpServletRequest request, HttpServletResponse response) throws IOException { // 1. 获取上传的文件 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartHttpServletRequest.getFile("file"); // 2. 设置保存路径 String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; File saveFile = new File(savePath); if (!saveFile.exists()) { saveFile.mkdir(); } // 3. 写入文件 String filename = file.getOriginalFilename(); File destFile = new File(savePath + filename); if (!destFile.exists()) { destFile.createNewFile(); } FileUtils.copyInputStreamToFile(file.getInputStream(), destFile); // 4. 返回结果 return "上传成功!"; } ``` 其,`MultipartHttpServletRequest`用于处理多媒体请求,`getFile("file")`方法用于获取上传的文件。`getRealPath("/")`方法获取当前Web应用的根目录,`FileUtils.copyInputStreamToFile()`方法用于将上传的文件写入磁盘。 最后,需要在`springmvc.xml`配置文件上传的相关Bean: ```xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="2097152"/> </bean> ``` 其,`CommonsMultipartResolver`是SpringMVC默认的文件上传解析器,`maxUploadSize`属性用于设置最大上传文件大小。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值