1、UploaderServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
Integer schunk = null;// 分割块数
Integer schunks = null;// 总分割数
String name = null;// 文件名
OutputStream outputStream = null;
InputStream inputStream = null;
PrintWriter pw = response.getWriter(); // 用于给前台反馈数据
String msg = "";
if (ServletFileUpload.isMultipartContent(request)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
factory.setRepository(new File(repositoryPath));// 设置临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(5 * 1024 * 1024);// 设置附近大小
List<FileItem> items = upload.parseRequest(request);
// 生成新文件名
String newFileName = null;
for (FileItem item : items) {
if (!item.isFormField()) {// 如果是文件类型
name = item.getName();// 获得文件名
// 第二次获取的是fileContent
// 将文件流存入dataInfo
System.out.println("file size = " + item.getSize());
inputStream = item.getInputStream();// 将上传的文件存入输入流中
newFileName = name;
if (name != null) {
String nFname = newFileName;
// 获取扩展名
String postfix = newFileName.substring(nFname
.lastIndexOf(".") + 1);
if (!"ini".equals(postfix) && !"txt".equals(postfix)) {
pw.println("上传文件必须为.ini或.txt文件!");
return;
}
if (schunk != null) {
nFname = schunk + "_" + name;
}
// 将dataInfo存入数据库
staLocationBO.saveBlob(dataInfo, inputStream);
System.out.println("文件写入数据库成功...");
// 写入到本地文件中
/*File savedFile = new File(uploadPath, nFname);
item.write(savedFile);*/
}
} else { // 表单类型
// 判断是否带分割信息
// 第一次获取的是hidden
String dwdName = items.get(0).getFieldName();
// 根据fieldName(dwdName)进行查询后存入StaLocation对象
dataInfo = staLocationBO.getDataById(dwdName);
if (item.getFieldName().equals("chunk")) {
schunk = Integer.parseInt(item.getString());
}
if (item.getFieldName().equals("chunks")) {
schunks = Integer.parseInt(item.getString());
}
}
}
// response.getWriter().write("{\"status\":true,\"newName\":\""+newFileName+"\"}");
msg = "文件上传成功!";
pw.println(msg);
} catch (FileUploadException e) {
logger.error(e.getMessage());
e.printStackTrace();
msg = "文件上传失败,请重试!";
pw.println(msg);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
msg = "文件上传失败,请重试!";
pw.println(msg);
} finally {
if (outputStream != null){
outputStream.close();
}
if(inputStream != null){
inputStream.close();
}
if (pw != null) {
pw.close();
}
}
}
}
@Override
public void init(ServletConfig config) throws ServletException {
repositoryPath = FileUtils.getTempDirectoryPath();
uploadPath = config.getServletContext().getRealPath(config.getInitParameter("uploadPath")); //如果上传到本地文件,在这里设置路径
File up = new File(uploadPath);
if(!up.exists()){
up.mkdir();
}
}
}
2、saveBlob方法
public void saveBlob(StaLocation staLocation,InputStream inputStream) throws Exception{
byte[] b = new byte[10240000];
int length = 0;
while ((length = inputStream.read(b)) != -1) {
Blob fileContent = getSessionFactory().getCurrentSession().getLobHelper().createBlob(b);
staLocation.setFileContent(fileContent);
}
getSessionFactory().getCurrentSession().saveOrUpdate(staLocation);
}
<form id = "upLoadForm" method="post" enctype="multipart/form-data">
<table class="csstable">
<tr>
<th align="center">
<label>电务段名称</label>
</th>
<td>
<span id="czmc"></span>
</td>
<th align="center">
<a id = "aDownLoad" href ="">下载</a>
</th>
</tr>
<tr>
<th align="center">
<input type = "file" name = "file" value = "浏览"/>
</th>
<th align="center">
<input type="submit" id = "upLoadButton" value = "上传" />
</th>
</tr>
</table>
</form>
$(document).ready(function () {
var ajax_option={
type : "post",
//url : "${pageContext.request.contextPath}/uploader",
url : "uploader",
dataType : "text",
// clearForm: true,
success : function(data) {
alert(data);
}
};
$('#upLoadForm').submit(function() { //当new_book这个form的submit事件被触发之时
//debugger;
$(this).ajaxSubmit(ajax_option); //用ajaxSubmit这个方法将new_book表单的内容提交到后台
return false;
});
});
5、引入jquery-form.js文件