文件上传的几种方式

来源:互联网 发布:生活在英国 知乎 编辑:程序博客网 时间:2024/05/29 14:47

SpringMVC+Jcrop截图插件+ajaxFileUpload

项目搭建

  1. Maven包导入
        <!-- J2EE 包 -->        <dependency>            <groupId>javax</groupId>            <artifactId>javaee-api</artifactId>            <version>7.0</version>        </dependency>        <!-- Spring MVC 核心包 -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>4.2.3.RELEASE</version>        </dependency>        <!-- 上传组件包 -->        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.3.1</version>        </dependency>        <dependency>            <groupId>commons-io</groupId>            <artifactId>commons-io</artifactId>            <version>2.4</version>        </dependency>        <dependency>            <groupId>commons-codec</groupId>            <artifactId>commons-codec</artifactId>            <version>1.9</version>        </dependency>        <!-- json -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>fastjson</artifactId>            <version>1.2.7</version>        </dependency>        <!-- json lang -->        <dependency>            <groupId>commons-lang</groupId>            <artifactId>commons-lang</artifactId>            <version>2.6</version>        </dependency>
  1. 配置文件
    总共有2个配置文件:springMVC.xml, system.properties
springMVC.xml----------<?xml version="1.0" encoding="UTF-8"?><beans        xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">    <!-- 组件扫描 -->    <context:component-scan base-package="com.liujianhome.controller"/>    <!-- 开启注解 -->    <mvc:annotation-driven/>    <!-- 静态资源处理 -->    <mvc:resources mapping="/css/**" location="/css/"/>    <mvc:resources mapping="/images/**" location="/image/"/>    <mvc:resources mapping="/js/**" location="/js/"/>    <mvc:default-servlet-handler/>    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!-- 默认编码 -->        <property name="defaultEncoding" value="utf-8"/>        <!-- 文件大小最大值 -->        <property name="maxUploadSize" value="10485760000"/>        <!-- 内存中的最大值 -->        <property name="maxInMemorySize" value="40960"/>    </bean></beans>system.properties----------file.path = /uploadfile/yrfh/userroot.file.path = E:/workspace/test/JcropDemo/target/Jcrop/
  1. 核心代码

html页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><html lang="en"><head>    <base href="<%=basePath%>">    <title>Jcrop Demo</title>    <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>    <script src="js/jquery.min.js"></script>    <script src="js/jquery.Jcrop.js"></script>    <script src="js/ajaxfileupload.js"></script>    <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css"/>    <script type="text/javascript">        var jcrop_api;        jQuery(function ($) {            // Create variables (in this scope) to hold the API and image size            var boundx,                    boundy,            // Grab some information about the preview pane                    $preview = $('#preview-pane'),                    $pcnt = $('#preview-pane .preview-container'),                    $pimg = $('#preview-pane .preview-container img'),                    xsize = $pcnt.width(),                    ysize = $pcnt.height();            $('#target').Jcrop({                onChange: updatePreview, // 选框改变时的事件                onSelect: updatePreview, // 选框选定时的事件                onRelease: clearCoords,  // 取消选框时的事件                boxWidth: 400,                aspectRatio: 200 / 200            }, function () {                // Use the API to get the real image size                var bounds = this.getBounds();                boundx = bounds[0];                boundy = bounds[1];                // Store the API in the jcrop_api variable                jcrop_api = this;                // Move the preview into the jcrop container for css positioning                $preview.appendTo(jcrop_api.ui.holder);            });            function updatePreview(c) {                if (parseInt(c.w) > 0) {                    var rx = xsize / c.w;                    var ry = ysize / c.h;                    $pimg.css({                        width: Math.round(rx * boundx) + 'px',                        height: Math.round(ry * boundy) + 'px',                        marginLeft: '-' + Math.round(rx * c.x) + 'px',                        marginTop: '-' + Math.round(ry * c.y) + 'px'                    });                }                $('#x1').val(c.x);                $('#y1').val(c.y);                $('#x2').val(c.x2);                $('#y2').val(c.y2);                $('#w').val(c.w);                $('#h').val(c.h);            };        });        function clearCoords() {            $('#coords input[type=text]').val('');        }        ;        function cutImg() {            // 提交裁剪图片            $.ajax({                type: "post",                url: "/doCutImg",                data: {                    "x": parseInt($("#x1").val()),                    "y": parseInt($("#y1").val()),                    "w": parseInt($("#w").val()),                    "h": parseInt($("#h").val()),                    "oldImg": $("#oldImg").val()                },                async: false,                success: function (data) {                    var jsonObj = eval("(" + data + ")");                    if (jsonObj.status == 1) {                        $("#cutImg").attr("src", jsonObj.path+"?t="+Math.random());                    } else {                        alert("图片上传失败!");                    }                }            });        }        function ajaxUpFile() {            $.ajaxFileUpload            (                    {                        url: '/ajaxFileUpload', //用于文件上传的服务器端请求地址                        secureuri: false, //是否需要安全协议,一般设置为false                        fileElementId: "ajaxFileId", //文件上传域的ID                        dataType: 'json', //返回值类型 一般设置为json                        data: {'format': 'gif,jpg,jpeg,png,bmp'},//                        data: {'format': 'gif,bmp'},                        success: function (data, status)  //服务器成功响应处理函数                        {                            if(data[0].status == 1) {                                $("#ajaxUpFileImg").attr("src", data[0].path);                            }else{                                alert(data[0].message);                            }                        },                        error: function (data, status, e)// 服务器响应失败处理函数                        {                            alert(data + "-" + e + "-" + status);                        }                    }            )        }    </script>    <style type="text/css">        /* Apply these styles only when #preview-pane has           been placed within the Jcrop widget */        .jcrop-holder #preview-pane {            display: block;            position: absolute;            z-index: 2000;            top: 10px;            right: -280px;            padding: 6px;            border: 1px rgba(0, 0, 0, .4) solid;            background-color: white;            -webkit-border-radius: 6px;            -moz-border-radius: 6px;            border-radius: 6px;            -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);            -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);            box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);        }        /* The Javascript code will set the aspect ratio of the crop           area based on the size of the thumbnail preview,           specified here */        #preview-pane .preview-container {            width: 250px;            height: 250px;            overflow: hidden;        }    </style></head><body><img src="/image/1111.jpg" id="target" alt="[Jcrop Example]"/><div id="preview-pane">    <div class="preview-container">        <img src="/image/1111.jpg" id="" class="jcrop-preview" alt="Preview"/>    </div></div><form id="coords" method="post"      class="coords"      action="">    <div class="inline-labels">        <label>X1 <input type="text" size="4" id="x1" name="x1"/></label>        <label>Y1 <input type="text" size="4" id="y1" name="y1"/></label>        <label>X2 <input type="text" size="4" id="x2" name="x2"/></label>        <label>Y2 <input type="text" size="4" id="y2" name="y2"/></label>        <label>W <input type="text" size="4" id="w" name="w"/></label>        <label>H <input type="text" size="4" id="h" name="h"/></label>        <input type="hidden" id="oldImg" value="/image/1111.jpg" name="oldImg"/>    </div>    <input type="button" onclick="cutImg()" value="上传截图"/></form><hr><img id="cutImg"><hr><h1>提交Form文件上传Demo</h1><form action="/doFileUpload" method="post" enctype="multipart/form-data">    <p><input type="file" name="file" id="file" value="普通文件"/></p>    <p><input type="submit" value="普通上传"/></p></form><hr><h1>用ajaxFileUpload上传Demo</h1><p><input type="file" name="ajaxFile" id="ajaxFileId" value="ajax上传文件"/></p><p><input type="button" onclick="ajaxUpFile()" value="ajax上传"/></p><p><img id="ajaxUpFileImg"/></p></body></html>

Java 代码

package com.liujianhome.controller;import com.liujianhome.util.*;import org.springframework.stereotype.Controller;import org.springframework.util.MultiValueMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.multipart.commons.CommonsMultipartFile;import org.springframework.web.multipart.commons.CommonsMultipartResolver;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.IOException;import java.util.List;import java.util.Map;/** * ! * * @author liujian * @version 2016/7/1 0001 */@Controllerpublic class JcropController {    @RequestMapping("/init")    public ModelAndView test() {        return new ModelAndView("/result.jsp");    }    /**     * 上传裁剪图片     *     * @param oldImg     * @param y     * @param x     * @param w     * @param h     * @return     */    @RequestMapping(value = "/doCutImg", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")    @ResponseBody    public String doCutImg(String oldImg, int y, int x, int w, int h, HttpServletRequest request) {        FileEntity fileEntity = null;        try {            fileEntity = FileCommon.saveImage(oldImg, y, x, w, h);            if (fileEntity.getStatus() == 1) {                return JsonUtils.toJsonString(fileEntity);            }        } catch (Exception e) {            e.printStackTrace();        }        return JsonUtils.toJsonString(fileEntity);    }    @RequestMapping(value = "/ajaxFileUpload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")    @ResponseBody    public String ajaxFileUpload(HttpServletRequest request, String format) {        List<FileEntity> resultList = FileCommon.doSuperUpFile(request, format);        String resultJson = JsonUtils.toJsonString(resultList);        return resultJson;    }    @RequestMapping(value = "/doFileUpload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")    public String doFileUpload(HttpServletRequest request) {        List<FileEntity> resultList = FileCommon.doSuperUpFile(request, null);        return "redirect:/init";    }}

几个Util包

package com.liujianhome.util;import org.springframework.util.Base64Utils;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;/** * ! * * @author liujian * @version 2016/6/13 0013 */public class Common {    /**     * 当前时间格式化!     * @param format     * @return     */    public static String getCurDateFormat(String format) {        SimpleDateFormat sdf = new SimpleDateFormat(format);        return sdf.format(new Date());    }}
package com.liujianhome.util;import org.springframework.util.MultiValueMap;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.multipart.commons.CommonsMultipartResolver;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.*;/** * 文件上传公共类! * * @author liujian * @version 2016/6/26 0026 */public class FileCommon {    /**     * 创建文件夹     *     * @param dir     */    private static void doDir(String dir) {        File file = new File(dir);        //如果文件夹不存在则创建        if (!file.exists() && !file.isDirectory()) {            file.mkdirs();        }    }    /**     * 文件上传,支持单个和多个     *     * @param request     * @param format  格式规定,例如:gif,jpg,jpeg,png,bmp     * @return     */    public static List<FileEntity> doSuperUpFile(HttpServletRequest request, String format) {        List<FileEntity> resultList = new ArrayList<FileEntity>();        // TODO 本地测试//        String rootPath = request.getServletContext().getRealPath("/");        String rootPath = SystemPropertiesUtil.getProperty("root.file.path");        // 定义允许上传的文件扩展名        HashMap<String, String> extMap = new HashMap<String, String>();        extMap.put("format", format);        //创建一个通用的多部分解析器        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());        //判断 request 是否有文件上传,即多部分请求        if (multipartResolver.isMultipart(request)) {            //转换成多部分request            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;            //取得request中的所有文件名            MultiValueMap<String, MultipartFile> iter = multiRequest.getMultiFileMap();            for (Map.Entry<String, List<MultipartFile>> entry : iter.entrySet()) {                //记录上传过程起始时的时间,用来计算上传时间                int pre = (int) System.currentTimeMillis();                //取得上传文件                MultipartFile file = multiRequest.getFile(entry.getKey());                if (format != null) {                    if (!Arrays.<String>asList(extMap.get("format").split(","))                            .contains(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1))) {                        FileEntity fileEntity = new FileEntity();                        fileEntity.setStatus(0);                        fileEntity.setMessage("上传文件扩展名只允许" + extMap.get("format") + "格式");                        resultList.add(fileEntity);                        return resultList;                    }                }                String fileName = FileCommon.doUpFile(rootPath, file);                if (!"".equals(fileName)) {                    FileEntity fileEntity = new FileEntity();                    fileEntity.setStatus(1);                    fileEntity.setMessage("上传成功");                    fileEntity.setPath(fileName);                    resultList.add(fileEntity);                }            }        }        return resultList;    }    /**     * 保存图片     *     * @param oldImg 原图路径     * @param top    选择框的左边y坐标     * @param left   选择框的左边x坐标     * @param width  选择框宽度     * @param height 选择框高度     * @return     * @throws IOException     */    public static FileEntity saveImage(String oldImg,                                       int top,                                       int left,                                       int width,                                       int height) throws IOException {        String rootFilePath = SystemPropertiesUtil.getProperty("root.file.path");        String newImg = oldImg.substring(0, oldImg.lastIndexOf("."));        String newImgSuf = ImageUtils.getExtension(oldImg).toLowerCase();        String newImgPathNotRoot = newImg + "_cut." + newImgSuf;        String newImgPath = rootFilePath + newImgPathNotRoot;        String oldImgPath = rootFilePath + oldImg;        File fileDest = new File(newImgPath);        if (!fileDest.getParentFile().exists())            fileDest.getParentFile().mkdirs();        String ext = ImageUtils.getExtension(newImgPath).toLowerCase();        BufferedImage bi = (BufferedImage) ImageIO.read(new File(oldImgPath));        height = Math.min(height, bi.getHeight());        width = Math.min(width, bi.getWidth());        if (height <= 0) height = bi.getHeight();        if (width <= 0) width = bi.getWidth();        top = Math.min(Math.max(0, top), bi.getHeight() - height);        left = Math.min(Math.max(0, left), bi.getWidth() - width);        BufferedImage bi_cropper = bi.getSubimage(left, top, width, height);        boolean flag = ImageIO.write(bi_cropper, ext, fileDest);        if (flag) {            FileEntity fileEntity = new FileEntity();            fileEntity.setPath(newImgPathNotRoot);            fileEntity.setMessage("上传成功");            fileEntity.setStatus(1);            return fileEntity;        } else {            FileEntity fileEntity = new FileEntity();            fileEntity.setMessage("上传失败");            fileEntity.setStatus(0);            return fileEntity;        }    }    /**     * 文件上传规则     *     * @param rootPath     * @param file     * @return     */    private static String doUpFile(String rootPath, MultipartFile file) {        if (file != null) {            //取得当前上传文件的文件名称            String myFileName = file.getOriginalFilename();            //如果名称不为“”,说明该文件存在,否则说明该文件不存在            if (myFileName.trim() != "") {                // 该项目的文件路径                String filePath = SystemPropertiesUtil.getProperty("file.path");                // 文件的相对路径                String relativeFilePath = filePath + "/" + Common.getCurDateFormat("yyyyMMdd");                // 文件的绝对路径                String absoluteFilePath = rootPath + relativeFilePath;                // 创建文件夹                doDir(absoluteFilePath);                // 重命名文件名                String fileName = System.currentTimeMillis() + "." + ImageUtils.getExtension(myFileName);                // 上传文件绝对路径                String path = absoluteFilePath + "/" + fileName;                File localFile = new File(path);                try {                    file.transferTo(localFile);                    return relativeFilePath + "/" + fileName;                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return "";    }}
package com.liujianhome.util;/** * 文件上传返回信息实体! * * @author liujian * @version 2016/7/7 0007 */public class FileEntity {    // 文件上传状态 (1:成功, 0:失败)    private int status;    // 文件上传地址    private String path;    // 上传状态消息    private String message;    public int getStatus() {        return status;    }    public void setStatus(int status) {        this.status = status;    }    public String getPath() {        return path;    }    public void setPath(String path) {        this.path = path;    }    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }}
package com.liujianhome.util;import java.io.File;/** * ! * * @author liujian * @version 2016/6/28 0028 */public class ImageUtils {    public static String getExtension(File f) {        return (f != null) ? getExtension(f.getName()) : "";    }    public static String getExtension(String filename) {        return getExtension(filename, "");    }    public static String getExtension(String filename, String defExt) {        if ((filename != null) && (filename.length() > 0)) {            int i = filename.lastIndexOf('.');            if ((i > -1) && (i < (filename.length() - 1))) {                return filename.substring(i + 1);            }        }        return defExt;    }    public static String trimExtension(String filename) {        if ((filename != null) && (filename.length() > 0)) {            int i = filename.lastIndexOf('.');            if ((i > -1) && (i < (filename.length()))) {                return filename.substring(0, i);            }        }        return filename;    }}
package com.liujianhome.util;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializeConfig;import com.alibaba.fastjson.serializer.SerializerFeature;import org.apache.commons.lang.StringUtils;import java.util.List;import java.util.Map;public class JsonUtils {    // fastjson 的序列化配置    public final static SerializeConfig      fastjson_serializeConfig_noYear = new SerializeConfig();    public final static SerializeConfig      fastjson_serializeConfig_time   = new SerializeConfig();    public final static SerializeConfig      fastjson_free_datetime          = new SerializeConfig();    // 默认打出所有属性(即使属性值为null)|属性排序输出,为了配合历史记录    private final static SerializerFeature[] fastJsonFeatures                = { SerializerFeature.WriteMapNullValue,            SerializerFeature.WriteEnumUsingToString, SerializerFeature.SortField };    public static <T>  T getValue(String text, String key, Class<T> clazz ) {        Map<String, String> map = (Map<String, String>) jsonToMap(text);        T result = (T) map.get(key);        return result;    }    public static <T> T parseObject(String item, Class<T> clazz) {        if (StringUtils.isBlank(item)) {            return null;        }        return JSON.parseObject(item, clazz);    }    public static final <T> List<T> parseArray(String text, Class<T> clazz) {        if (StringUtils.isBlank(text)) {            return null;        }        return JSON.parseArray(text, clazz);    }    public static String toJsonString(Object object) {        return toJsonString(object, fastjson_serializeConfig_noYear);    }    public static String toJsonString(Object object, SerializeConfig serializeConfig) {        if (null == object) {            return "";        }        return JSON.toJSONString(object, serializeConfig, fastJsonFeatures);    }    public static Map<?, ?> jsonToMap(String json) {        if (StringUtils.isBlank(json)) {            return null;        }        return (Map<?, ?>) JSON.parse(json);    }    public static Map<?, ?> objectToMap(Object object) {        String json = toJsonString(object);        if (StringUtils.isBlank(json)) {            return null;        }        return (Map<?, ?>) JSON.parse(json);    }    public static String mapToJson(Map<?, ?> params) {        if (null == params || params.isEmpty()) {            return null;        }        return JSON.toJSONString(params, true);    }}
package com.liujianhome.util;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * ! * * @author liujian * @version 2016/5/23 0023 */public class SystemPropertiesUtil {    static Properties prop = new Properties();    static {        InputStream in = SystemPropertiesUtil.class.getResourceAsStream("/system.properties");        try {            prop.load(in);        } catch (IOException e) {            e.printStackTrace();        }    }    public static String getProperty(String key) {        String value = prop.getProperty(key).trim();        return value;    }}
0 0
原创粉丝点击