效果图
数据表
准备存储文件的数据表,
需要字段:数据id,文件长度,数据内容,内容类型,文件名
一,文件上传
样式代码:
<label for="uploadfiles" class="control-label" style="float:left;padding-left:15px;"></label>
<br/>
<span id="filename" style="vertical-align: middle">未上传文件</span>
<div class="file-container" style="display:inline-block;position:relative;overflow: hidden;vertical-align:middle">
<input type="file" id="uploadfiles" name="uploadfiles" onchange="loadFile(this.files[0])" style="position:absolute;top:0;left:0;font-size:34px; opacity:0">
<button class="btn btn-success" type="button" style="margin-right: 0px; ">选择文件</button><br/>
</div>
<div style="position: fixed;display:inline-block;position:relative;overflow: hidden;vertical-align:middle">
<button class="btn btn-default bi-btn-width90" onclick="uploadFile()" type="button" >上传</button>
</div>
<div id="loadtips" style="text-align: center; clear: both; color:#FF0000;display:none">
数据导入中,请稍候...
</div>
js代码:
function uploadFile(){
$("#loadtips").show();
var datas={id:$("#id").val()};
$.ajaxFileUpload
(
{
url: '/**/upload?id='+$("#id").val(),
secureuri: false,
fileElementId: "uploadfiles",
data:datas,
dataType: 'json',
success: function (data)
{
$("#loadtips").hide();
if(data.success)
{
dLong.layerInfo("文件上传成功")
$("#fileid").val(data.filename[0]);
}else{
dLong.layerError(data.msg)
}
},
}
)
}
后端代码:
//文件上传,上传文件信息至数据库
/**
* 图片上传,支持多文件上传,request里面的filesroad参数存放该文件准确存放的表字段信息
*
* @param request
* @param response
* @throws Exception
*/
import org.springframework.web.multipart.MultipartFile;
@RequestMapping(value = "upload")
@ResponseBody
public String dbfileUpload(@RequestParam MultipartFile[] uploadfiles,@RequestParam HashMap<String, String> param, HttpServletRequest request, HttpServletResponse response){
Map<String, String> filesroadMap = new HashMap<>();
String name = "";
//判断文件类型
for (int i = 0; i < uploadfiles.length; i++) {
MultipartFile multipartFile = uploadfiles[i];
String filename = multipartFile.getOriginalFilename();
//获取后缀名称
String fileNameExt =filename.lastIndexOf(".")>-1?filename.substring(filename.lastIndexOf(".")+1, filename.length()):"";
String[] split = Public.sysConfig.getProperty("wenjianshangchuan").split(",");
name=fileNameExt.trim();
int num=0;
for (String s : split) {
if (fileNameExt.trim().equalsIgnoreCase(s)){
num++;
}
}
if (num==0){
Map resultMap = new HashMap<>();
resultMap.put("success", false);
resultMap.put("msg", "不可上传"+fileNameExt.trim()+"格式文件");
resultMap.put("filename", filename);
resultMap.put("code",1);//0表示成功,1失败
return JSON.toJSONString(resultMap);
}
}
List filenames = new LinkedList<>();
List filenamesOrg = new LinkedList<>();
Connection connection = null;
//将文件信息插入数据库表中
try {
connection = dlBaseJdbcTemplate.getDataSource().getConnection();
for (int i = 0; i < uploadfiles.length; i++) {
MultipartFile multipartFile = uploadfiles[i];
//判断是否为空并上传
if (Util.checkNotNull(multipartFile) && Util.checkNotNull(multipartFile.getOriginalFilename())) {
String dataId = UUID.randomUUID().toString();
StringBuilder sqlbuilder=new StringBuilder();
sqlbuilder.append(" insert into form_file (");
sqlbuilder.append(" id,datacontent,fileNameOrg,fileLength,contentType");
sqlbuilder.append(" ) values (");
sqlbuilder.append(" ?,?,?,?,?");
sqlbuilder.append(" )");
PreparedStatement preparedStatement = connection.prepareStatement(sqlbuilder.toString());
preparedStatement.setString(1, dataId);
preparedStatement.setBinaryStream(2, multipartFile.getInputStream());
preparedStatement.setString(3, multipartFile.getOriginalFilename());
preparedStatement.setLong(4, multipartFile.getSize());
preparedStatement.setString(5, multipartFile.getContentType());
preparedStatement.execute();
preparedStatement.close();;
filenames.add(dataId);
filenamesOrg.add(multipartFile.getOriginalFilename());
}
}
//返回全路径数据
Map resultMap = new HashMap<>();
resultMap.put("success", true);
resultMap.put("msg", "上传成功.");
resultMap.put("filename", filenames);
resultMap.put("filenameorg", filenamesOrg);
return JSON.toJSONString(resultMap);
} catch (Exception ex) {
logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常:" + ex.getMessage(), ex);
Map resultMap = new HashMap<>();
resultMap.put("success", false);
resultMap.put("msg", "系统错误,请稍候再试." + ex.getMessage().replace("\r", "").replace("\n", ""));
resultMap.put("filename", filenames);
resultMap.put("filenameorg", filenamesOrg);
return JSON.toJSONString(resultMap);
} finally {
DataSourceUtils.releaseConnection(connection,dlBaseJdbcTemplate.getDataSource());
}
}
二,文件下载
1,介绍
ServletOutputStream类提供了将二进制数据写入响应的流。这是一个抽象类。
2,使用
ServletResponse接口的getOutputStream()方法返回ServletOutputStream类的实例。
ServletOutputStream out=response.getOutputStream();
3,读取上传之后的文件
@RequestMapping("downmodel")
public HashMap<String, Object> getForminfobyid(@RequestParam HashMap<String, Object> param, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
FileEntity fileEntity = FileEntityDao.findallbyid(param.get("id").toString());
String contentType = fileEntity.getContentType();
response.setContentType(StringUtil.isEmptyOrLength0(contentType) ? "application/octet-stream" : contentType);
String inputStreamFileName = fileEntity.getFileNameOrg();
if (!StringUtil.isEmptyOrLength0(request.getParameter("gettype")) && "download".equalsIgnoreCase(request.getParameter("gettype"))) {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(inputStreamFileName, "UTF-8"));
}
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.write(crfFormFileEntity.getDatacontent());
servletOutputStream.flush();
HashMap<String, Object> hashMap=createResult(Boolean.TRUE,"操作成功。");
hashMap.put("entity",entity);
return hashMap;
}catch (Exception e){
logger.error("系统错误!" + e.getMessage(), e);
return createResult(Boolean.FALSE, "操作失败。");
}
}