ChengDuXiuu
4/21/2020 - 11:44 PM

Java整合FastDFS实现文件上传至服务器、以及整合Nginx实现预览上传的图片

@RequestMapping("/upload")
    public Result upload(MultipartFile file, String userid) {
        try {
            User user = userService.upload(file, userid);

            if(user != null) {
                System.out.println(user);
                return new Result(true, "上传成功", user);
            }
            else {
                return new Result(false, "上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "上传失败");
        }
    }
@Override
    public User upload(MultipartFile file, String userid) {
        try {
            // 返回在FastDFS中的URL路径,这个路径是不带http://192.168.25.133/..
            String url = fastDFSClient.uploadFace(file);
            // 在FastDFS上传的时候,会自动生成一个缩略图
            // 文件名_150x150.后缀
            String[] fileNameList = url.split("\\.");
            String fileName = fileNameList[0];
            String ext = fileNameList[1];

            String picSmallUrl = fileName + "_150x150." + ext;

            String prefix = env.getProperty("fdfs.httpurl");
            TbUser tbUser = userMapper.selectByPrimaryKey(userid);

            // 设置头像大图片
            tbUser.setPicNormal(prefix + url);
            // 设置头像小图片
            tbUser.setPicSmall(prefix + picSmallUrl);
            // 将新的头像URL更新到数据库中
            userMapper.updateByPrimaryKey(tbUser);

            // 将用户信息返回到Controller
            User user = new User();
            BeanUtils.copyProperties(tbUser, user);

            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
package com.itheima.hchat.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FastDFSClient {

	@Autowired
	private FastFileStorageClient storageClient;

//	@Autowired
//	private AppConfig appConfig; // 项目参数配置

	/**
	 * 上传文件
	 * 
	 * @param file
	 *            文件对象
	 * @return 文件访问地址
	 * @throws IOException
	 */
	public String uploadFile(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
				FilenameUtils.getExtension(file.getOriginalFilename()), null);

		return storePath.getGroup() + "/" + storePath.getPath();
	}

	public String uploadFile(File file) throws IOException {
		StorePath storePath = storageClient.uploadFile(new FileInputStream(file), FileUtils.sizeOf(file),
				FilenameUtils.getExtension(file.getName()), null);

		return storePath.getGroup() + "/" + storePath.getPath();
	}
	
	public String uploadFile2(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
				FilenameUtils.getExtension(file.getOriginalFilename()), null);

		return storePath.getGroup() + "/" + storePath.getPath();
	}
	
	public String uploadQRCode(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
				"png", null);
		
		return storePath.getGroup() + "/" + storePath.getPath();
	}
	
	public String uploadFace(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
				"png", null);
		
		return storePath.getGroup() + "/" + storePath.getPath();
	}
	
	public String uploadBase64(MultipartFile file) throws IOException {
		StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
				"png", null);
		
		return storePath.getGroup() + "/" + storePath.getPath();
	}
	
	/**
	 * 将一段字符串生成一个文件上传
	 * 
	 * @param content
	 *            文件内容
	 * @param fileExtension
	 * @return
	 */
	public String uploadFile(String content, String fileExtension) {
		byte[] buff = content.getBytes(Charset.forName("UTF-8"));
		ByteArrayInputStream stream = new ByteArrayInputStream(buff);
		StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
		return storePath.getGroup() + "/" + storePath.getPath();
	}

	// 封装图片完整URL地址
//	private String getResAccessUrl(StorePath storePath) {
//		String fileUrl = AppConstants.HTTP_PRODOCOL + appConfig.getResHost() + ":" + appConfig.getFdfsStoragePort()
//				+ "/" + storePath.getFullPath();
//		return fileUrl;
//	}

	/**
	 * 删除文件
	 * 
	 * @param fileUrl
	 *            文件访问地址
	 * @return
	 */
	public void deleteFile(String fileUrl) {
		if (StringUtils.isEmpty(fileUrl)) {
			return;
		}
		try {
			StorePath storePath = StorePath.praseFromUrl(fileUrl);
			storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
		} catch (FdfsUnsupportStorePathException e) {
			e.getMessage();
		}
	}
}
// -------
						// 后端TODO:
						// 设置后端用于上传文件的地址
						// 后端应返回带头像完整URL的用户信息
						// -------
						var task = plus.uploader.createUpload(config.SERVER_URL + "/user/upload", {
								method: "POST",
								blocksize: 204800,
								priority: 100
							},
							function(t, status) {
								// 上传完成
								if(status == 200) {

									var data = JSON.parse(t.responseText);
									console.log(JSON.stringify(data));

									if(data.success) {
										// 加载当前图片
										myphoto.src = data.result.picNormal;
										// 更新用户信息
										user.picNormal = data.result.picNormal;
										user.picSmall = data.result.picSmall;
										util.saveUser(user);

										// 获取main_me的webview
										var main_me = plus.webview.getWebviewById("main_me.html");
										// 触发refresh自定义事件
										mui.fire(main_me, "refresh");
									} else {
										mui.toast("上传失败");
									}
								} else {
									mui.toast("上传失败");
								}
							}
						);
						task.addFile(path, {
							key: "file"
						});
						task.addData("userid", user.id);
						//task.addEventListener( "statechanged", onStateChanged, false );
						task.start();