springmvc中使用webuploader上传多张图片;maven中读取配置文件中的属性(路径)

工作中用到了这里,要上传多张图片,但是调试的过程中发现会出现路径问题,特此记录,供大家参考吧

前提:自行下载webuploader工具包

jsp文件(js一并写在这里):

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}" scope="request"></c:set>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>webuploader image demo</title>

<link rel="stylesheet" href="${ctx}/resources/uploader/webuploader.css">
<script src="${ctx}/resources/js/jquery.js"></script>
<script src="${ctx}/resources/uploader/webuploader.min.js"></script>
</head>
<body>

<h3>图片上传</h3>
<!--dom结构部分-->
<div id="uploader-demo">
<!--用来存放item-->
<div id="fileList" class="uploader-list"></div>
<div id="upInfo" ></div>
<div id="filePicker">选择文件</div>
</div>
<input type="button" id="btn" value="开始上传">
<script>
    // 图片上传demo
    jQuery(function() {
        var $ = jQuery,
                $list = $('#fileList'),
        // 优化retina, 在retina下这个值是2
                ratio = window.devicePixelRatio || 1,
        // 缩略图大小
                thumbnailWidth = 100 * ratio,
                thumbnailHeight = 100 * ratio,
        // Web Uploader实例
                uploader;
        // 初始化Web Uploader
        uploader = WebUploader.create({
            // 自动上传。
            auto: false,
            // swf文件路径
            swf : BASE_URL + '/resources/uploader/Uploader.swf',
            server : BASE_URL + '/ttt',
            threads:'5',        //同时运行5个线程传输
            fileNumLimit:'10',  //文件总数量只能选择10个

            // 选择文件的按钮。可选。
            pick: {id:'#filePicker',  //选择文件的按钮
                multiple:true},   //允许可以同时选择多个图片
            // 图片质量,只有type为`image/jpeg`的时候才有效。
            quality: 90,

            //限制传输文件类型,accept可以不写
            accept: {
                title: 'Images',//描述
                extensions: 'gif,jpg,jpeg,bmp,png,zip',//类型
                mimeTypes: 'image/*'//mime类型
            }
        });


        // 当有文件添加进来的时候,创建img显示缩略图使用
        uploader.on( 'fileQueued', function( file ) {
            var $li = $(
                            '<div id="' + file.id + '" class="file-item thumbnail">' +
                            '<img>' +
                            '<div class="info">' + file.name + '</div>' +
                            '</div>'
                    ),
                    $img = $li.find('img');

            // $list为容器jQuery实例
            $list.append( $li );

            // 创建缩略图
            // 如果为非图片文件,可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }

                $img.attr( 'src', src );
            }, thumbnailWidth, thumbnailHeight );
        });

        // 文件上传过程中创建进度条实时显示。    uploadProgress事件:上传过程中触发,携带上传进度。 file文件对象 percentage传输进度 Nuber类型
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                    $percent = $li.find('.progress span');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo( $li )
                        .find('span');
            }

            $percent.css( 'width', percentage * 100 + '%' );
        });

        // 文件上传成功时候触发,给item添加成功class, 用样式标记上传成功。 file:文件对象,    response:服务器返回数据
        uploader.on( 'uploadSuccess', function( file,response) {
            $( '#'+file.id ).addClass('upload-state-done');
            //console.info(response);
            $("#upInfo").html("<font color='red'>"+response._raw+"</font>");
        });

        // 文件上传失败                                file:文件对象 , code:出错代码
        uploader.on( 'uploadError', function(file,code) {
            var $li = $( '#'+file.id ),
                    $error = $li.find('div.error');

            // 避免重复创建
            if ( !$error.length ) {
                $error = $('<div class="error"></div>').appendTo( $li );
            }

            $error.text('上传失败!');
        });

        // 不管成功或者失败,文件上传完成时触发。 file: 文件对象
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').remove();
        });

        //绑定提交事件
        $("#btn").click(function() {
            console.log("上传...");
            uploader.upload();   //执行手动提交
            console.log("上传成功");
        });

    });
</script>
<script>
    var BASE_URL = "${ctx}";
</script>
</body>


Java类文件
package org.xxz.webuploader;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/24.
 */
@Controller
public class UpLoadeController {
    @RequestMapping(value = "/ttt", method = RequestMethod.POST)
    public void upload(HttpServletRequest request, HttpServletResponse response){
        System.out.println("收到图片!");
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> files = Murequest.getFileMap();//得到文件map对象
        String upaloadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";//得到当前工程路径拼接上文件名
        File dir = new File(upaloadUrl);
        System.out.println(upaloadUrl);
        if(!dir.exists())//目录不存在则创建
            dir.mkdirs();
        for(MultipartFile file :files.values()){
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            File  tagetFile = new File(upaloadUrl+fileName);//创建文件对象
            if(!tagetFile.exists()){//文件名不存在 则新建文件,并将文件复制到新建文件中
                try {
                    tagetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    file.transferTo(tagetFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        System.out.println("接收完毕");
    }
}
项目中要配置文件的路径作为上传路径,使用以下工具类

package com.yyny.sellelec.common.utils;

import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtil {
	public static Properties getConfig() {
		Properties property = new Properties();
		try {
			ClassLoader classLoader = PropertiesUtil.class.getClassLoader();
			InputStream in = classLoader.getResourceAsStream("application.properties");
			property.load(in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return property;
	}

	public static String getPropertyParam(String key) {
		Properties property = new Properties();
		try {
			ClassLoader classLoader = PropertiesUtil.class.getClassLoader();
			InputStream in = classLoader.getResourceAsStream("application.properties");
			property.load(in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return property.getProperty(key);
	}

//	public static void main(String[] args) {
//		System.out.println(PropertiesUtil.getPropertyParam("storeDir"));
//	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值