Ver código fonte

冲突解决

huangzhiyong 6 anos atrás
pai
commit
54376fc8c3

+ 99 - 65
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/dfs/FastDFSController.java

@ -13,16 +13,18 @@ import com.yihu.jw.rm.health.house.HealthyHouseMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
/**
@ -43,13 +45,6 @@ public class FastDFSController extends EnvelopRestEndpoint {
    @Value("${img.path}")
    private String img_path;
    private final ResourceLoader resourceLoader;
    @Autowired
    public FastDFSController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    /**
     * 文件上传 - 返回相关索引信息
     *
@ -68,29 +63,25 @@ public class FastDFSController extends EnvelopRestEndpoint {
            @ApiParam(name = "objectId", value = "被创建文件所属对象标识", required = true)
            @RequestParam(value = "objectId") String objectId) throws Exception {
        String fileName = file.getOriginalFilename();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (fileExtension.equals(fileName)) {
            fileExtension = "file";
        //需要随机生成一个uuid作为文件名,防止冲突
        int dot = fileName.lastIndexOf('.');
        if (dot>0) {
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(dot);
            String path = upload(file.getInputStream(), newFileName);
            //路径存储到mysql数据库
            FileResource fileResource = new FileResource();
            fileResource.setObjectId(objectId);
            fileResource.setStoragePath(path);
            fileResource.setFileSize(String.valueOf(file.getSize()));
            fileResource.setFileName(fileName);
            fileResource.setCreateUser(creator);
            fileResource = fileResourceService.save(fileResource);
            fileResource.setStoragePath(path);
            return success(fileResource);
        }else {
            return failed("文件格式不正确",ObjEnvelop.class);
        }
        //上传
//需要随机生成一个uuid作为文件名,防止冲突
        String path = upload(file.getInputStream(), fileName);
//        ObjectNode objectNode = fastDFSUtil.upload(file.getInputStream(), fileExtension, "svr-dfs");
//        String groupName = objectNode.get(FastDFSUtil.GROUP_NAME).toString();
//        String remoteFileName = objectNode.get(FastDFSUtil.REMOTE_FILE_NAME).toString();
//        int fileSize = objectNode.get(FastDFSUtil.FILE_SIZE).asInt();
//        String path = groupName.substring(1, groupName.length() - 1) + ":" + remoteFileName.substring(1, remoteFileName.length() - 1);
        //路径存储到mysql数据库
        FileResource fileResource = new FileResource();
        fileResource.setObjectId(objectId);
        fileResource.setStoragePath(path);
//        fileResource.setFileSize(String.valueOf(fileSize));
        fileResource.setFileName(fileName);
        fileResource.setCreateUser(creator);
        fileResource = fileResourceService.save(fileResource);
//        path = groupName.substring(1, groupName.length() - 1) + "/" + remoteFileName.substring(1, remoteFileName.length() - 1);
        fileResource.setStoragePath(path);
        return success(fileResource);
    }
    /**
@ -111,25 +102,22 @@ public class FastDFSController extends EnvelopRestEndpoint {
        byte[] bytes = Base64.getDecoder().decode(fileStr);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String fileName = paramMap.get("fileName");
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (fileExtension.equals(fileName)) {
            fileExtension = "file";
        int dot = fileName.lastIndexOf('.');
        if (dot>0) {
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(dot);
            String path = upload(inputStream, newFileName);
            //路径存储到mysql数据库
            FileResource fileResource = new FileResource();
            fileResource.setObjectId(paramMap.get("object"));
            fileResource.setStoragePath(path);
            fileResource.setFileSize(String.valueOf(bytes.length));
            fileResource.setFileName(fileName);
            fileResource = fileResourceService.save(fileResource);
            fileResource.setStoragePath(path);
            return success(fileResource);
        }else {
            return failed("文件格式不正确!",ObjEnvelop.class);
        }
        ObjectNode objectNode = fastDFSUtil.upload(inputStream, fileExtension, "svr-dfs");
        int fileSize = objectNode.get(FastDFSUtil.FILE_SIZE).asInt();
        String groupName = objectNode.get(FastDFSUtil.GROUP_NAME).toString();
        String remoteFileName = objectNode.get(FastDFSUtil.REMOTE_FILE_NAME).toString();
        String path = groupName.substring(1, groupName.length() - 1) + ":" + remoteFileName.substring(1, remoteFileName.length() - 1);
        //路径存储到mysql数据库
        FileResource fileResource = new FileResource();
        fileResource.setObjectId(paramMap.get("object"));
        fileResource.setStoragePath(path);
        fileResource.setFileSize(String.valueOf(fileSize));
        fileResource.setFileName(fileName);
        fileResource = fileResourceService.save(fileResource);
        path = groupName.substring(1, groupName.length() - 1) + "/" + remoteFileName.substring(1, remoteFileName.length() - 1);
        fileResource.setStoragePath(path);
        return success(fileResource);
    }
    /**
@ -200,9 +188,7 @@ public class FastDFSController extends EnvelopRestEndpoint {
            @RequestParam(value = "id") String id) throws Exception {
        FileResource fileResource = fileResourceService.findById(id);
        String storagePath = fileResource.getStoragePath();
        String groupName = storagePath.split(":")[0];
        String remoteFileName = storagePath.split(":")[1];
        byte[] bytes = fastDFSUtil.download(groupName, remoteFileName);
        byte[] bytes = load(storagePath);
        String fileStream = new String(Base64.getEncoder().encode(bytes));
        if (!StringUtils.isEmpty(fileStream)) {
            return success(fileStream);
@ -225,9 +211,7 @@ public class FastDFSController extends EnvelopRestEndpoint {
        if (path.split(":").length < 2) {
            return failed("参数有误");
        }
        String groupName = path.split(":")[0];
        String remoteFileName = path.split(":")[1];
        byte[] bytes = fastDFSUtil.download(groupName, remoteFileName);
        byte[] bytes = load(path);
        String fileStream = new String(Base64.getEncoder().encode(bytes));
        if (!StringUtils.isEmpty(fileStream)) {
            return success(fileStream);
@ -235,10 +219,15 @@ public class FastDFSController extends EnvelopRestEndpoint {
        return failed("FileStream Is Empty");
    }
    /**
     * 文件上传
     * @param inputStream
     * @param fileName
     * @return
     */
    public String upload(InputStream inputStream, String fileName) {
        OutputStream outputStream = null;
        String path1 = img_path + "\\" + fileName;
        String path1 = img_path + "/" + fileName;
        try {
            //文件源
            File files = new File(img_path);
@ -272,20 +261,65 @@ public class FastDFSController extends EnvelopRestEndpoint {
    }
    /**
     * 显示单张图片
     * 文件下载
     *
     * @param filename
     * @param fileSize
     * @return
     * @throws IOException
     */
    @RequestMapping("show")
    public ResponseEntity showPhotos(String fileName){
    public byte[] downLoad(String filename, int fileSize) throws IOException {
        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            // 由于是读取本机的文件,file是一定要加上的, path是在application配置文件中的路径
            return ResponseEntity.ok(resourceLoader.getResource("file:" + img_path + fileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
            in = new BufferedInputStream(new FileInputStream(f));
            byte[] buffer = new byte[fileSize];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, fileSize))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }
    public byte[] load(String filename) throws IOException {
        FileChannel fc = null;
        try {
            fc = new RandomAccessFile(filename, "r").getChannel();
            MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,
                    fc.size()).load();
            System.out.println(byteBuffer.isLoaded());
            byte[] result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                fc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

+ 2 - 1
svr/svr-healthy-house/src/main/resources/application.yml

@ -86,7 +86,8 @@ fastDFS:
jw:
  smsUrl: http://svr-base:10020/sms_gateway/send
img:
  path: E:/tryfile/upload/img
  #path: E:/tryfile/upload/img  //测试
  path: /root/uploadFiles/
---
spring: