温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

webuploader+springmvc实现图片上传功能

发布时间:2020-09-26 17:39:17 来源:脚本之家 阅读:175 作者:MAZN36 栏目:编程语言

本文为大家分享了webuploader springmvc实现图片上传的具体代码,供大家参考,具体内容如下

jsp文件

<%@ 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>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/manage/Widget/webuploader/0.1.5/webuploader.css" rel="external nofollow" >
<script src="${pageContext.request.contextPath}/manage/assets/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/manage/Widget/webuploader/0.1.5/webuploader.js"></script>
</head>
<body>
 <h4>图片上传</h4>
 <!--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:'${pageContext.request.contextPath }/manage/Widget/webuploader/0.1.5/Uploader.swf',
 // 文件接收服务端。
 server: '${pageContext.request.contextPath }/uploader.action',
 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("上传成功");
 alert("上传成功!");
 });

});
</script>
</body>
</html>

springMvc 的 servlet加入以下代码(允许上传):

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

引入的包

commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar

java代码

package com.shopping.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @author MAZN 
 * @date 创建时间:2017年5月2日 下午10:02:36
 * @parameter
 * @return 
 */
@Controller
public class UploadImgController {
 int counter = 0;


 @RequestMapping("/uploader")
 public void upload(HttpServletRequest request,HttpServletResponse response){

 //String fileName;
 // File tagetFile;
 System.out.println("收到图片!");
 MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest)request;
 Map<String, MultipartFile> files = Murequest.getFileMap();//得到文件map对象
 //String upaloadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";//得到当前工程路径拼接上文件名
 String t=Thread.currentThread().getContextClassLoader().getResource("").getPath(); 
 int num=t.indexOf(".metadata");
 String small = "small";
 String upaloadUrl=t.substring(1,num).replace('/', '\\')+"image\\"+small+"\\";
 //+"项目名\\WebContent\\文件";
 File dir = new File(upaloadUrl);
 System.out.println(upaloadUrl);
 String img_url = upaloadUrl;//图片路径
 if(!dir.exists())//目录不存在则创建
 dir.mkdirs();
 for(MultipartFile file :files.values()){
 counter++;
 String fileName=file.getOriginalFilename();
 File tagetFile = new File(upaloadUrl+fileName);//创建文件对象
 img_url += 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(img_url);
 System.out.println("接收完毕"+counter);
 }
}

参考:WebUploader客户端批量上传图片 后台使用springMVC

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI