//这是看的大神的。
//原地址:https://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html $("#sub").click(function(){
$.ajaxFileUpload({
url:'<%=_basePath%>uploadZiZhi',
secureuri:false,//是否启用安全机制
fileElementId:'file',//file的id
dataType: 'json/text',//返回的类型
success: function (data) {//调用成功时怎么处理
//alert(data)
var jo = eval("("+data+")");
alert(jo.name)
window.opener.backsPort('<%=inputId%>',data.id,data.name);
window.close();
} });
});
<script src="${pageContext.request.contextPath}/po/js/jquery.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/po/js/ajaxfileupload.js" type="text/javascript"></script>
后台代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { System.out.println("上传资质------------");
Session session= new Session(PoConnection.get());
String userid = request.getParameter("userid");
String type = request.getParameter("type");
if("license".equals(type)){
//营业执照
type="1";
}else if("authorization".equals(type)){
//委托代理人授权书
type="2";
}else if("qualifications".equals(type)){
//产品或施工资质
type="3";
}else if("bankInfo".equals(type)){
//开户行信息
type="4";
}else{
throw new RuntimeException("上传失败!");
}
//删除原来资质附件
session.executeUpdate("delete from PO_SRM_INFO_FILE where type='"+type+"'AND FK_SRM="+userid);
// 1 创建解析器工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 1.1 配置上传流在接收时缓冲区的大小 => 默认是10kb
factory.setSizeThreshold(1024 * 10);
// 1.2 配置上传时临时文件所在的目录 => 制定一个地址
// factory.setRepository(new File("e://temp"));
// 获得java 临时文件所在的目录
String sysTem = System.getProperty("java.io.tmpdir");
System.out.println(sysTem);
// ------------------------------------------------------------------
// 2 创建解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 2.1 判断当前request对象是否是多段式请求
if (!upload.isMultipartContent(request)) {
throw new RuntimeException("您不是多段是请求!");
}
// 设置段头使用什么码表编码 => 默认Latin码表
upload.setHeaderEncoding("utf-8");
// 设置文件的大小 , 上传时如果超过这个大小会抛出异常
upload.setFileSizeMax(1024 * 1000*10);// 设置单个上传文件的大小
upload.setSizeMax(1024 * 1000*10);// 设置单次上传的总文件大小
// 解析request对象 => 会把多段式中的每一个段都封装成一个FileItem对象
List<FileItem> list = null;
try {
list = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
// ----------------------------------------------------
// FileItem 代表多段式提交中每段内容
StringBuilder idStr = new StringBuilder();
StringBuilder fileNameStr = new StringBuilder(); PreparedStatement pstmt = null;
if (list != null) {
for (FileItem item : list) {
if (item.isFormField()) {
// 普通表单字段
String key = item.getFieldName();// 获得普通表单字段中的键
String value = item.getString("Utf-8");// 获得普通表单字段中的值----指定编码解决中文乱码的问题
} else {
// 文件上传段
String fileName = item.getName();
if(EcUtil.isEmptyString(fileName)){
throw new RuntimeException("未选择文件!");
}
// System.out.println("上传的文件名称:"+fileName);
String filetype = fileName.substring(fileName.lastIndexOf(".")+1); // 获得文件的内容
InputStream is = item.getInputStream(); //TODO 将数据存入数据库
String id = session.queryForColumn(String.class, " SELECT PO_SRM_INFO_FILE_SEQ.NEXTVAL from dual"); String sql = "insert into PO_SRM_INFO_FILE(ID,CONTENT,TITLE,OP_TIME,TYPE,DELSTATUS,FK_SRM,FILETYPE) values("+id+",?,?,?,?,?,?,?)";
try { ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = is.read(buffer))) {
output.write(buffer, 0, n);
}
pstmt = session.currentConnection().prepareStatement(sql);
pstmt.setBinaryStream(1, new ByteArrayInputStream(output.toByteArray()),output.toByteArray().length);
pstmt.setString(2, fileName);
pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
pstmt.setString(4, type);
pstmt.setString(5, "0");
pstmt.setString(6, userid);
pstmt.setString(7, filetype);
pstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
session.roolback();
} // 关闭流
is.close();
// 删除临时文件
item.delete(); //返回的id和文件名拼接
if(fileNameStr.length() > 0){
fileNameStr.append(",").append(fileName);
}else{
fileNameStr.append(fileName);
}
if(idStr.length() > 0){
idStr.append(",").append(id);
}else{
idStr.append(id);
} }
}
}
//写出
JSONObject jo = new JSONObject();
jo.put("id", idStr.toString());
jo.put("name", fileNameStr.toString());
response.getWriter().write(jo.toString());
return;
}