前台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>
引用的index.js:
$(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);
}
}
可以看到的是利用百度的webuploader上传文件还是十分的简单
希望对你有所帮助