背景:spring ,spring MVC,已拥有所需的jar,配置了文件解析器,fastdfs已部署
前端
(记得在form加上属性method="post" enctype="multipart/form-data")
http://blog.youkuaiyun.com/hunwanjie/article/details/79642159
后台
spring mvc
注入(别忘了xml加依赖):
@Autowired private FastDFSClient fastDFSClient;方法:
@RequestMapping(value="/editUser",method = RequestMethod.POST) public ResponseEntity<Map<String, Object>> saveModel(User user, @RequestParam Long id, @RequestParam("uploadFile")MultipartFile multipartFile) { try { //读取图片流;如果是图片则不会出现异常 BufferedImage image = ImageIO.read(multipartFile.getInputStream()); // 用于删除原有的头像图片 User u = userService.queryById(user.getId()); // 上传新的头像 // 上传文件的后缀名称 String file_ext_name = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(), "."); byte[] local_filename = multipartFile.getBytes(); String url = fastDFSClient.uploadFile(local_filename, file_ext_name); // 设置图片路径 user.setSysPicture(url); userService.updateSelective(user); setResultSuccess(); // 删除原有的图片 fastDFSClient.removeFile(u.getSysPicture()); return ResponseEntity.ok().body(result); // 200 } catch (Exception e) { e.printStackTrace(); setResultFailure(e.getMessage()); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); // 500 }
fastdfs
package com.realwill.fastdfs; import org.csource.common.MyException; import org.csource.fastdfs.*; import java.io.IOException; /** * Date:2018/3/21 * Author: 柯文阳 * Desc: 文件服务器客户端 */ public class FastDFSClient { // 用于切割url获取文件存储位置 private static final String ADDR = "http://120.0.0.1/"; private static TrackerClient trackerClient = null; private static TrackerServer trackerServer = null; private static StorageServer storageServer = null; private static StorageClient storageClient = null; public FastDFSClient(){ } static { // 配置文件路径 // 设置tracker server地址 String path = FastDFSClient.class.getClassLoader().getResource("tracker.conf").getPath(); try { ClientGlobal.init(path); trackerClient = new TrackerClient(); // 通过trackerClient,创建trackerServer trackerServer = trackerClient.getConnection(); // 创建storageClient 参数storageServer:没有专门的storageServer storageClient = new StorageClient(trackerServer, storageServer); }catch (Exception e){ e.printStackTrace(); } } /** * 上传 * @param local_filename * @param file_ext_name * @return * @throws IOException * @throws MyException */ public String uploadFile(byte[] local_filename,String file_ext_name) throws IOException, MyException { String s = new String(local_filename); // 上传文件 // 第一个参数为本地的图片路径C:\Users\Administrator\Desktop\RealWill.png,第二个参数为图片的后缀png,第三个为文件的信息可以设置为null String[] fileInfos = storageClient.upload_file(local_filename,file_ext_name, null); // 获取存储服务器信息 if (fileInfos !=null && fileInfos.length>1){ // 第一个值是组名,第二个是相对路径;两个字符串拼接后是完整图片路径 for (String fileInfo : fileInfos) { //group1 //M00/00/00/rBD8vlqxsxiAdixQAABVq--SqTg455.png System.out.println(fileInfo); } // 第一个参数为追踪服务器,第二个参数为组名,第三个参数为文件相对路径 ServerInfo[] fetchStorage = trackerClient.getFetchStorages(trackerServer, fileInfos[0], fileInfos[1]); for (ServerInfo serverInfo : fetchStorage) { System.out.println("ipAddr=" + serverInfo.getIpAddr()+";port=" + serverInfo.getPort());//ipAddr=120.78.169.220;port=23000 } // 拼接完整可访问的路径;存储服务器的组对应的服务器没有组内集群的时候一般只有一个. // 而存储服务器上使用了nginx,使用80端口访问具体图片 String url = "http://" + fetchStorage[0].getIpAddr() + "/" + fileInfos[0] + "/" + fileInfos[1]; System.out.println(url); return url; } return null; } /** * 下载 * @param url http://120.78.169.220/ group1/M00/00/00/rBD8vlqxsxiAdixQAABVq--SqTg455.png * 切割成storagePath 文件的全部路径 如:group1/M00/00/00/rBD8vlqxsxiAdixQAABVq--SqTg455.png * @throws IOException * @throws MyException -1失败,0成功 2没有该资源 */ public void removeFile(String url) throws IOException, MyException { // 第一个参数组名,第二个参数文件相对路径 String[] storagePath = url.split(ADDR); String[] split = storagePath[1].split("/", 2); String group_name = split[0]; String remote_filename = split[1]; // 参数一:group1 参数二:M00/00/00/rBD8vlqxsxiAdixQAABVq--SqTg455.png int result = storageClient.delete_file(group_name,remote_filename); if (result < 0){ throw new MyException("删除fastdfs文件:"+storagePath+"失败"); } } }
conf配置:
内容:
tracker_server=120.0.0.1:22122
注: