最近在看文件上传的问题,之前配置了搭建了SpringMVC的项目,这个地方我们是用百度的webuploader上传文件,让后SpringMVC框架的接收文件。
我们来看一下相关的代码:
首页是页面文件index.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>
然后对应的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();
}
});
});
上面是对应的js文件,那么上传后台是如何来接收相关的文件:
package com.wdg.controller;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RestController;
import com.wdg.domain.FileInfo;
import com.wdg.util.CommonDao;
@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(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.info("-------------------开始调用上传文件upload接口212-------------------");
FileInfo fileinfo=new FileInfo();
fileinfo.setAttachguid(UUID.randomUUID().toString());
fileinfo.setDate(new Date());
String name = request.getParameter("name");// 文件名称
String type = name.substring(name.lastIndexOf(".") + 1);// 文件类型
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;// 拼接路径
ServletInputStream inputStream = request.getInputStream();// ***获取字节流,图片保存在这里,切记这里只可以获取一次。***
File uploadFile = new File(path);// 路径文件,一定要有文件夹,没有则创建,mkdir
FileCopyUtils.copy(inputStream, new FileOutputStream(uploadFile));// 复制图片
inputStream.close();// 关闭io,这里写的简陋了些,代码从简
//String realPath= uploadFile.getPath();//realPath 为图片真路径
InputStream iStream = new FileInputStream(uploadFile);
byte[] data = new byte[] {};
data = inputStreamToByte(iStream);//将文件保存到字节数组中
fileinfo.setFilecontent(data);
fileinfo.setFilename(name);
double filesize = request.getContentLength();//获取源文件大小
fileinfo.setFilesize(filesize);
CommonDao.getInstance().insert(fileinfo);
log.info("-------------------结束调用上传文件upload接口-------------------");
return "ok";
}
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;
}
}
上面我们是将文件存入到数据库,并且将文件存入到项目的相对的路径。