java中文件的上传比较简单
主要包括:文件名生成,文件传输,数据库更新三大部分
1.控制层的处理器方法
@RequestMapping(value = "upload/{id}.do")
public ResultVo<Team> fileUpload(@RequestParam("logo")MultipartFile myfile, HttpServletRequest request,@PathVariable("id") Integer teamId){
String path = request.getServletContext().getRealPath("/img/uploadFile/");
String originalFilename = myfile.getOriginalFilename();
String randomName = UUID.randomUUID().toString().replace("-", "");
int i = originalFilename.lastIndexOf(".");
String substring = originalFilename.substring(i);
String logoName = randomName + substring;
int num=0;
try {
myfile.transferTo(new File(path+"/"+logoName));
System.out.println("上传成功!"+path+"/"+logoName);
Team team = new Team();
team.setTeamId(teamId);
team.setTeamLogo(logoName);
Integer integer = teamService.updateTeam(team);
if (integer == 1) {
return new ResultVo<>();
}
return new ResultVo<>("500","服务器内部错误,请稍后再试");
} catch (IOException e) {
return new ResultVo<>("500","上传出错,错误代码:"+e.getMessage());
}
}
先生成不重复的文件名和路径
拼接路径,传输文件到指定位置
数据库动态更新,抛出异常
updateByPrimaryKeySelective()是动态更新,可以看之前的文章
2.前端页面部分,首先已有数据的内容要查询展示,这里是queryById的请求,就此掠过
function queryAndShowInfo(teamId){
$.ajax({
type: "GET",
url: "/team/"+teamId+".do",
data: "",
success: function (vo) {
let obj=vo.object;
let teamId=obj.teamId;
let teamLogo=obj.teamLogo;
let teamName=obj.teamName;
let chineseName=obj.chineseName;
$("input[name='chineseName']").val(chineseName);
if(teamLogo!=null){
$("img[name='teamLogo']").attr("src","/img/uploadFile/"+teamLogo);
}else{
$("img[name='teamLogo']").addClass("hidden");
$("img[name='teamLogo']").parent().html("还没有上传logo图片");
}
}
});
}
文件ajax的上传整体实现
$(function () {
let url = document.location.toString();
let pageNum=url.GetValue("pageNum");
let pageSize=url.GetValue("pageSize");
let teamId=url.GetValue("teamId");
$("input[name='pageNum']").val(pageNum);
$("input[name='pageSize']").val(pageSize);
$("input[name='teamId']").val(teamId);
queryAndShowInfo(teamId);
myUploadLogo(teamId,pageNum,pageSize);
});
function myUploadLogo(teamId,pageNum,pageSize) {
$("#logo").fileinput({
uploadUrl:"/team/upload/"+teamId+".do",
uploadAsync : true,
showUpload : true,
showRemove : true,
showCaption : true,
showPreview : true,
dropZoneEnabled : false,
maxFileCount : 1,
enctype : 'multipart/form-data',
validateInitialCount : true,
msgFilesTooMany : "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
allowedFileTypes : [ 'image' ],
allowedPreviewTypes : [ 'image' ],
language : 'zh'
});
$('#logo').on('fileerror', function(event, data, msg) {
alert("上传失败!"+msg);
});
$("#logo").on("fileuploaded", function(event, data, previewId, index) {
let ref = $(this).attr("data-ref");
$("input[name='" + ref + "']").val(data.response.url);
window.location.href = "/pages/team/list.html?pageNum="+pageNum+"&pageSize="+pageSize;
});
}
|