使用WebUploader上传文件,后台Java保存

前台html页面:

<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="resources/webuploader/webuploader.css">
<link rel="stylesheet" type="text/css" href="resources/css/boostrap/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="resources/css/boostrap/bootstrap.min.css">
 
<script type="text/javascript" src="resources/js/jquery-1.11.0.min.js"></script>
</head>
<body>
	<div id="uploader" class="wu-example">
		<!--用来存放文件信息-->
		<div id="thelist" class="uploader-list"></div>
		<div class="btns">
			<div id="picker">选择文件</div>
			<button id="ctlBtn" class="btn btn-default">开始上传</button>
		</div>
	</div>
	<script type="text/javascript"
		src="resources/webuploader/webuploader.js"></script>
	<script type="text/javascript" src="resources/js/index.js"></script>
</body>
</html>

Javascript:

$(function() {
	var $list = $("#thelist");
	var $btn = $("#ctlBtn");
	var state = 'pending'; // 上传文件初始化
	var uploader = WebUploader.create({
		swf : 'webuploader/Uploader.swf',
		server : 'http://localhost:8080/Shopping/filecontroller/upload',
		pick : '#picker',
		resize : false
	});
	uploader.on('fileQueued', function(file) {
		$list.append('<div id="' + file.id + '" class="item">'
				+ '<h4 class="info">' + file.name + '</h4>'
				+ '<p class="state">等待上传...</p>' + '</div>');
	});
 
	uploader.on('uploadProgress',function(file, percentage) {
        var $li = $('#' + file.id), $percent = $li.find('.progress .progress-bar');
 
		// 避免重复创建
		if (!$percent.length) {
		    $percent = $('<div class="progress progress-striped active">'
            + '<div class="progress-bar" role="progressbar" style="width: 0%">'
            + '</div>' + '</div>').appendTo($li).find('.progress-bar');
		}
 
        $li.find('p.state').text('上传中');
 
        $percent.css('width', percentage * 100 + '%');
    });
	
 
	uploader.on('uploadSuccess', function(file) {
		$('#' + file.id).find('p.state').text('已上传');
	});
 
	uploader.on('uploadError', function(file) {
		$('#' + file.id).find('p.state').text('上传出错');
	});
 
	uploader.on('uploadComplete', function(file) {
		$('#' + file.id).find('.progress').fadeOut();
	});
	$btn.on('click', function() {
		if (state === 'uploading') {
			uploader.stop();
		} else {
			uploader.upload();
		}
	});
 
});

后台的Java Controller:

package com.wdg.controller;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
import com.alibaba.fastjson.JSONObject;
import com.wdg.util.BuildJsonOfObject;
 
@RestController
@RequestMapping("/filecontroller")
public class UploadFileController {
 
	private Logger log;
 
	public UploadFileController() {
		this.log = Logger.getLogger(this.getClass());
	}
 
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam("file")MultipartFile files,HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 上传服务器的同时,可以进行数据库的入库
        JSONObject json=new JSONObject();
		response.setCharacterEncoding("utf-8");
		String msg = "添加成功";
		log.info("-------------------开始调用上传文件upload接口-------------------");
		try{
		String name = files.getOriginalFilename();
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		int index = path.indexOf("Shopping");
		path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/";
		path = path + File.separator + name;
		File uploadFile = new File(path);
		files.transferTo(uploadFile);
		}catch(Exception e){
			msg="添加失败";
		}
		log.info("-------------------结束调用上传文件upload接口-------------------");
		json.put("msg", msg);
		return BuildJsonOfObject.buildJsonOfJsonObject(json);
	}
 
	/*private byte[] inputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bAOutputStream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bAOutputStream.write(ch);
		}
		byte data[] = bAOutputStream.toByteArray();
		bAOutputStream.close();
		return data;
	}*/
 
	@RequestMapping(value = "/uploadservlet", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	protected String uploadServlet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JSONObject json=new JSONObject();
		response.setCharacterEncoding("utf-8");
		String msg = "添加成功";
		log.info("-------------------开始调用上传文件uploadservlet接口-------------------");
		try {
			if (request instanceof MultipartHttpServletRequest) {
				MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
				List<MultipartFile> multipartFile = mr.getFiles("myfile");
				if (null != multipartFile && !multipartFile.isEmpty()) {
					MultipartFile file = multipartFile.get(0);
					String name = file.getOriginalFilename();
					String path = this.getClass().getClassLoader().getResource("/").getPath();
					int index = path.indexOf("Shopping");
					path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/";
					path = path + File.separator + name;
					File uploadFile = new File(path);
					if(FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadFile))>0)
					{
						json.put("path",path);
					}
				
				}
			}
		} catch (Exception e) {
			msg = "上传失败";
		}
		log.info("-------------------结束调用上传文件uploadservlet接口-------------------");
		json.put("msg", msg);
		return BuildJsonOfObject.buildJsonOfJsonObject(json);
	}
}

转自:https://blog.csdn.net/datouniao1/article/details/79716268

官网:http://fex.baidu.com/webuploader/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值