springboot+jquery
<div class="form-group">
<label class="col-sm-3 control-label">头像:</label>
<div class="col-sm-8">
<input id="photo" name="photo" class="form-control" type="file">
</div>
</div>
var photo=$("#photo").val();
if(photo!=null && photo!=""){
// 构建数据
var data = new FormData()
data.append('name', $('[name=photo]').val())
data.append('file', $('[name=photo]')[0].files[0]) // file 对象
$.ajax({
cache : false,
type : "POST",
url : "/upload",
data :data,
processData: false,//数据不被转换为字符串
contentType: false,//上传文件时使用,避免 JQuery 对其操作
async : false,
dataType:"json",
error : function(request) {
},
success : function(data) {
if (data.code == 0) {
photo = data.fileName;
}
}
});
}
package com.bootdo.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}
package com.bootdo.util;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("")
public class uploadController extends BaseController {
private String pathName="D://springboot//tomcat//upload/";
@ResponseBody
@PostMapping("/upload")
R upload(MultipartFile file, HttpServletRequest request) {
String fileName = file.getOriginalFilename();
fileName = FileUtil.renameToUUID(fileName);
try {
FileUtil.uploadFile(file.getBytes(), pathName, fileName);
return R.ok().put("fileName","/upload/"+fileName);
} catch (Exception e) {
e.printStackTrace();
}
return R.error();
}
}
ps:文件之前是放在tomcat临时文件下的,但是每次服务重启就不是之前的tomcat临时文件了,所以之前上传到服务器的图片,再查找路径就不对,就会找不到图片,所以,后来改成放在本地路径,并把资源映射改到本地路径:
package com.bootdo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 资源映射路径
*/
@Configuration
public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/springboot/tomcat/upload/");
}
}
ps:添加之后想让图片显示在列表:
获取url路径
var href = location.host;
if(href.indexOf("http://")<0 && href.indexOf("https://")<0){
href="http://"+href;
}
bootstrapTable放formatter
{
field : 'photo',
title : '头像' ,
formatter : function(value, row, index) {
if(value!=null && value!= ""){
return "<img style='width: 70px;height: 30px;' src='"+href+value+"' alt=''>"
}
}
},
还有一个大问题,点击修改的时候如何给文件赋值,等我再找找吧