Spring MVC在maven下用$ajaxFileUpload()上传图片

来源:互联网 发布:宿迁12345网络问政电话 编辑:程序博客网 时间:2024/05/16 11:27

工作准备

jsp:需要导入jquery.min.js和ajaxfileupload.js后台:在speing的applicationContext.xml配置文件中加入
<!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver -->    <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"                p:defaultEncoding="UTF-8"                p:maxUploadSize="5400000"                p:uploadTempDir="fileUpload/temp"    >    </beans:bean>

要是没有相应的jar包,就在pom.xml中配置一下。
因为重点是文件上传,页面就简介的来了。

代码

test.jsp

<%--  Created by IntelliJ IDEA.  User: qqg  Date: 2017/8/10  Time: 14:53  To change this template use File | Settings | File Templates.--%><%@ page language="java" contentType="text/html; charset=utf-8"         pageEncoding="utf-8"%><%    String path = request.getContextPath();    HttpSession s = request.getSession();    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html><head>    <script type="text/javascript" src="/js/jquery.min.js"></script>    <script type="text/javascript" src="/js/ajaxfileupload.js"></script>    <title>Title</title></head><body><form action="/editImage"  method="post" enctype="multipart/form-data" >    <div> 图片显示    <img src=""  id="img_box_update" style="height: 200px;width: 350px;"/>    </div>    <hr><br>    <input type="file" name="file" class="form-control" id="file_update" >    <br>    <hr>    <div>        上传后得到的url:    <input type="text" name="avatar" class="form-control" id="input_update_avatar" style="width: 700px;">    </div></form><input type="submit"  id="img_update"  value="上传图片"/></body><script>    $("#img_update").click(function () {        $.ajaxFileUpload({            //处理文件上传操作的服务器端地址            url:'/editImage',            secureuri:false,                          //是否启用安全提交,默认为false            fileElementId:'file_update',               //文件选择框的id属性            type:"POST",            dataType:'text',                           //服务器返回的格式,可以是json或xml等            success:function(result){            //服务器响应成功时的处理函数                console.log(result);                //alert(result);                // img.appendTo("#img_box");                $("#input_update_avatar").val(result);                $("#img_box_update").prop("src",result);            },            error:function(data, status, e){ //服务器响应失败时的处理函数                //$('#result').html("<font color=\"red\"> 图片上传失败,请重试!!</font><br/>");            }        });    });</script></html>

控制器TestController.java

package com.hand.controller;import com.hand.util.FileUpload;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.commons.CommonsMultipartFile;import javax.servlet.http.HttpServletRequest;import java.io.IOException;/** * Created by qqg on 2017/8/14. */@Controllerpublic class TestController {    @ResponseBody    @RequestMapping(value="/editImage")    public String editTbReportImage(@RequestParam("file") final CommonsMultipartFile file            ,HttpServletRequest request) {        String filePath = null;        //System.out.println("root path:"+request.getContextPath());        if (!file.isEmpty()) {            try {                filePath =  FileUpload.uploadFile(file,request);            } catch (IOException e) {                e.printStackTrace();            }        }        System.out.println("filePath"+filePath);        return filePath;    }}

文件上传工具类FileUpload.java

package com.hand.util;//import org.apache.commons.io.FileUtils;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.IOException;import java.util.Date;/** * Created by qqg on 2017/8/12. */    public class FileUpload {    public static final String FILE_PATH = "/images/upload/";    //文件上传    public static String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {    //项目对应服务器的根目录,用这个方法都可以获取        String s = request.getSession().getServletContext().getRealPath("/");        //测试的,在服务器的根目录下创建个文件测试一下        System.out.println("5:"+ s);        File file_root = new File(s+"/images/HelloWorld.txt");        if(!file_root.exists()){            try {                file_root.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        }        System.out.println("file_text path is:"+file_root.getAbsolutePath());        String file_root_img = s +  FILE_PATH;        String fileName = file.getOriginalFilename();        String file_last = new Date().getTime() + String.valueOf(fileName);        File tempFile = new File(file_root_img, file_last);        if (!tempFile.getParentFile().exists()) {            tempFile.getParentFile().mkdir();        }        if (!tempFile.exists()) {            tempFile.createNewFile();        }        file.transferTo(tempFile);        //输出绝对地址看看        System.out.println(tempFile.getAbsolutePath());        //返回的不能是绝对地址,只能返回相对于服务器的地址,因为jsp图片显示的时候会在图片前面自动的加上 http://localhost:8080/ProjectName,这里返回后面的一段就好,到时候jsp页面会自己拼接完整的url        return    FILE_PATH + file_last;    }    public static File getFile(String fileName) {        return new File(FILE_PATH, fileName);    }}

注意事项:

1.jsp页面中的

<input type="file" name="file" class="form-control" id="file_update" >其中的id对应$ajaxFileUpload();方法中的
fileElementId:’file_update’, 的值,俩个的值要一样。

2.有什么不对的地方看看注释。

界面截图

这里写图片描述
这里写图片描述

总结:

图片上传不难,难点在于路径。我们上传不能上传到web项目中,而是要上传到web项目发布的服务器中,然后在数据库中保存相对于服务器的相对地址即可。还有,要是想用$ajax();这个方法上传图片的话,要将文件Formdate,才能上传。