ajax上传文件并且判断是否为空
程序员文章站
2024-02-19 19:28:28
...
HTML
<div>
<input type="file" id = "file" >
<button id="but">确定</button>
</div>
jquery
$("#but").click(function(){
var format=new FormData();
format.append("img",$('#file')[0].files[0]);//括号中第一个引号中写key第二个为值
$.ajax({
//几个参数需要注意一下
type: "post",//方法类型
url: "/addFile",//url
data:format,
dataType:"json",
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
async:false,
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (0==result ) {
alert("修改失败");
}else{
alert("修改成功");
};
},
error : function() {
alert("请稍后重试!");
}
})
});
java controller
/**
* 添加文件
* @param fileEntity
* @return
*/
@PostMapping("addFile")
public int addFile(HttpServletRequest request, FileEntity fileEntity){
return operationService.addFile(request,fileEntity);
}
java service
//文件上传
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
if (null!=mr.getMultiFileMap().get("img")) {//判断是否有文件
String systemPath = null;
String path = "/upload/";
try {
systemPath = ResourceUtils.getURL("classpath:static").getPath().replace("%20", " ").replace('/', '\\').substring(1);//从路径字符串中取出工程路径
} catch (Exception e) {
e.printStackTrace();
}
String[] imgs = {"img"};
String[] imgUrl = UploadFile.getFileURL(mr, imgs, systemPath, path);//上传文件公共方法
fileEntity.setImgUrl(imgUrl[0]);
}else{
fileEntity.setImgUrl("");
}
java 文件上传公共方法
/**
* 通过;spring 的方法解析所有方法
* @param multipartRequest 请求
* @param keys 获取参数key 对应的文件 key的值必须和前台页面的name值一样
* @param systemPath 系统路径(活路径)
* @param path 自己目录的路径
* @return
*/
public static String[] getFileURL(MultipartHttpServletRequest multipartRequest, String[] keys, String systemPath, String path){
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String[] vales=new String[keys.length];
for (int i=0;i<keys.length;i++) {
vales[i]=getPathValue(fileMap.get(keys[i]),systemPath,path);
}
return vales;
}
protected static String getPathValue(MultipartFile file,String systemPath,String path){
if (!file.isEmpty()) {
try {
String fileName=file.getOriginalFilename();
if(StringUtils.isNotBlank(fileName)){
String[] str=fileName.split("\\.");
if(str.length==1){
path=path+new Date().getTime()+str[0]+".JPEG";
}else{
path=path+new Date().getTime()+"."+str[str.length-1];
}
}
// 文件保存路径
File fl=new File(systemPath+path);
if(!fl.getParentFile().exists()){
fl.getParentFile().mkdirs();
}
// 转存文件
file.transferTo(fl);
} catch (Exception e) {
e.printStackTrace();
}
}else{
return null;
}
return path;
}
ps:如果有其他参数和文件一起上传,都需要放到format中
转载于:https://my.oschina.net/u/3535099/blog/3080966
上一篇: 判断上传文件是否为图片
下一篇: nodejs环境配置