springboot实现文件上传步骤解析
这篇文章主要介绍了springboot实现文件上传步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
第一步编写上传的前段页面
单个文件上传 文档入库 
这篇文章主要介绍了springboot实现文件上传步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
第一步编写上传的前段页面
单个文件上传 文档入库 
第二步写对应的js页面
/**
*@Name:historyStorageCtrl,井史数据入库
*@Date:2019-06-19
*@Author:huofenwei
*/
(function(angular){
'usestrict';
angular.module('Lujing').controller('historyStorageCtrl',['$scope','$http','ToastService','$compile','$timeout','HttpService','$filter',
function($scope,$http,ToastService,$compile,$timeout,HttpService,$filter){
$scope.fileInvalid=false;
var$fileInput=initFileInput("importFile",'/server/search/upload');
/**
*初始化文件上传
*/
functioninitFileInput(ctrlName,uploadUrl){
varcontrol=$('#'+ctrlName);
control.fileinput({
language:'zh',
uploadUrl:uploadUrl,//上传的地址
allowedFileExtensions:['doc','docx','xls','xlsx','ppt','pptx','pdf','mp4','avi','wmv','asf','asx','rm','rmvb','3gp','mov','m4v','dat','mkv','flv','vob'],
showUpload:true,//是否显示上传按钮
showCaption:true,//是否显示标题
showPreview:false,//是否显示预览区域
browseClass:"btnbtn-primary",//按钮样式
previewFileIcon:"",
}).on('fileuploaderror',fileuploaderror).on("fileuploaded",function(event,data,previewId,index){
//console.log(data);.on('fileselect',fileselect)
$scope.$apply(function(){
$scope.fileId=data.response.fileId;//未执行
$scope.document.fileName=data.files[0].name;
});
}).on("filecleared",function(event,data,msg){
$scope.$apply(function(){
$scope.fileInvalid=false;
});
});
returncontrol;
}
/**
*清空输入框
*/
functionimportClearFunc(){
if($fileInput)
$fileInput.fileinput('clear');
$scope.fileInvalid=false;
}
/**
*文件上传错误
**/
functionfileuploaderror(event,data,msg){
$scope.fileInvalid=true;
$scope.$apply();
$('.modal-body.kv-upload-progress').css('display','none');
if(!(data.jqXHR.responseJSON)){//文件类型验证错误
$('#fileError').html(msg);
}else{//上传错误
console.log(data);
varstatusCode=data.jqXHR.responseJSON.message;
varerrorMsg=HTTP_ERROR_MAP[''+statusCode];
$('#fileError').html(errorMsg);
}
}
/**
*add打开添加模态框
*/
$scope.openAddModal=function(){
$scope.document={};
$scope.document.classificationId=1;
$scope.document.starGrade=5;
$timeout(importClearFunc);
//openModeldialog();
};
/**
*表单验证
*@returns{boolean}
*/
functionformVlidate(){
if(!$scope.document.introduction){
returnfalse;
}
if(!$scope.document.keyPackage){
returnfalse;
}
returntrue;
}
/**
*提交表单信息
*/
$scope.submitFileInfo=function(){
if(!$scope.fileId){
//ToastService.alert("提示","先上传文件,再提交表单","info");
console.error("先上传文件,再提交表单");
return;
}
if(!formVlidate()){
//ToastService.alert("提示","请填充表单","info");
console.error("请填充表单");
return;
}
$scope.params={
'introduction':$scope.document.introduction,//简介
'keyPackage':$scope.document.keyPackage,//可能查询的关键字
'starGrade':$scope.document.starGrade,//星级
'classificationId':$scope.document.classificationId,//文件的id
'filePath':$scope.fileId,//文件的路径
'docName':$scope.document.fileName,//文件的名字
'author':$scope.document.author,
'unit':$scope.document.unit,
'writeDate':$scope.document.writeDate?$scope.document.writeDate.format("yyyy-MM-ddhh:mm:ss"):$scope.document.writeDate,
'jh':$scope.document.jh,
'id':$scope.document.id
};
HttpService.post("/server/search/submit",$scope.params).then(function(data){
$('#documentOprModal').modal('hide');
//$("#contTable").bootstrapTable('refresh');
console.error("提交文件信息成功");
},function(response){
//ToastService.alert("提示","提交文件信息出错","warning");
console.error("提交文件信息出错");
});
}
}
])
})(angular); 
第三部编写后台上传文件和提交表单的代码
packagecom.shiwen.yitihui.server.controller;
importjava.io.File;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.UUID;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RequestBody;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importorg.springframework.web.multipart.MultipartFile;
importcom.shiwen.yitihui.common.Snowflake;
importcom.shiwen.yitihui.domain.DocClassification;
importcom.shiwen.yitihui.domain.DocType;
importcom.shiwen.yitihui.domain.DocumentFile;
importcom.shiwen.yitihui.domain.FileEntity;
importcom.shiwen.yitihui.server.service.DocumentFileService;
/**
*@authorwangjie:
*@version创建时间:2019年8月26日上午11:54:22
*@Description类描述:
*/
@RestController
@RequestMapping("/search")
publicclassUploadFileController{
	
	@Autowired
	privateDocumentFileServicedfservice;
	
	privateStringuploadPath="E://file";
	
	/**
	*上传文件
	*@paramfile
	*@return
	*/
	@PostMapping("/upload")
	publicMapuploadFile(MultipartFilefile){
		Mapmap=newHashMap();
		try{
//文件的对象
			FileEntityfEntity=newFileEntity();
			Stringuuid=UUID.randomUUID().toString();
			//文件的id
			fEntity.setId(uuid.replaceAll("-",""));//String.valueOf(Snowflake.getNextKey()));
			//文件的名字
			fEntity.setFileName(file.getOriginalFilename());
			//上传文件的时间
			fEntity.setUploadTime(newDate());
			//上传者
			fEntity.setUploadBy("admin");
			//文件的后缀
			Stringsuffix=fEntity.getFileName().substring(fEntity.getFileName().indexOf("."));
			//文件存放的完整路径
			fEntity.setFinePathName(uploadPath+File.separator+fEntity.getId()+suffix);
			//文件的类型
			fEntity.setDocType(newDocType());
			//设置文件的类型
			fEntity.getDocType().setId(getDocTypeId(fEntity.getFileName()));
			//创建文件的对象
			FilenewFile=newFile(fEntity.getFinePathName());
			//上传文件
			file.transferTo(newFile);
			map.put("result","success");
			map.put("fileId",fEntity.getId());
		}catch(Exceptione){
//			e.printStackTrace();
			map.put("result","fail");
		}
		returnmap;
		
	}
	
	/**
	*提交表单
	*@paramdf
	*@return
	*/
	@PostMapping("/submit")
	publicMapsubmitFileInfo(@RequestBodyDocumentFiledf){
		Mapmap=newHashMap();
		try{
			if(df.getId()==null||df.getId().isEmpty()||df.getId()==""){
				df.setId(String.valueOf(Snowflake.getNextKey()));
			}
			Stringsuffix=df.getDocName().substring(df.getDocName().indexOf("."));
			df.setFilePath(uploadPath+File.separator+df.getFilePath()+suffix);
			df.setUploadBy("admin");//用户名称df.setUploadTime(newjava.util.Date());
			df.setUploadTime(newDate());
			df.setDownloadNumber(0L);
			df.setHeat(0L);
			df.setRelated(20);
			df.setDocType(newDocType());
			df.getDocType().setId(getDocTypeId(suffix));
			df.setClassification(newDocClassification());
			df.getClassification().setId(df.getClassificationId());
			dfservice.save(df);
			map.put("result","success");
		}catch(Exceptione){
			//e.printStackTrace();
		map.put("result","fail");
		}
		returnmap;
	}
	
	
	
	privateIntegergetDocTypeId(StringfileName){
		if(fileName.contains(".doc")){
			return1;
		}elseif(fileName.contains(".xls")){
			return2;
		}elseif(fileName.contains(".pdf")){
			return3;
		}elseif(fileName.contains(".ppt")){
			return4;
		}else{
			return5;
		}
	}
}      
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。