美文网首页
前端上传图片保存到本地静态资源路径下,再通过url获取

前端上传图片保存到本地静态资源路径下,再通过url获取

作者: 墨色尘埃 | 来源:发表于2018-11-06 18:14 被阅读464次

文件上传到本机目录①,将①再设置为静态资源路径,前端获取文件的方式就方便了很多。
智慧工地和财务项目中就是这么做的,如下:
application-prod.yml配置中,文件保存到本地的路径为photoPath: F:/Files/invoice,静态资源路径为static-locations: file:/F:/Files/invoice
最后通过如下规则url可以访问到图片htttp://host:port/files/mh/{name}
http://127.0.0.1:10003/2018-11-05/4e121f8047c1420389cf6767a380e764_360%E6%88%AA%E5%9B%BE16460528504596.png
InvoiceFileController

server:
  port: 10003

spring:
  resources:
    static-locations: file:/F:/Files/invoice  #静态资源路径
#    static-locations: file:/D:/files/sitemanage  服务器上文件所在地址
#    访问时,直接在浏览器输入,因为指定到了某个目录,所以这个目录不用在url中显示
#    访问地址  http://172.16.11.66:10003/20180726/{文件名}

.............
#目录①
pathConfig:
  photoPath: F:/Files/invoice
@RestController
@RequestMapping("/api/file")
public class InvoiceFileController extends BaseRestController<InvoiceFileService, InvoiceFileMapper, InvoiceFile,
        String> {

    @Value("${pathConfig.photoPath}")
    private String photoPath;

    /**
     * 上传文件接口
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public ResponseObj<String> uploadFile(HttpServletRequest request) throws Exception {

        int size;
        boolean result = false;  // 初始化 影响行数
        String urlList = "";
        boolean flag = false;
        InvoiceFile invoiceFile = new InvoiceFile();

        if (request instanceof MultipartHttpServletRequest) {
            try {
                String json = request.getParameter("content");
                if (!StringUtils.isEmpty(json)) {
                    ObjectMapper oMapper = new ObjectMapper();
                    oMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                    invoiceFile = oMapper.readValue(json, InvoiceFile.class);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = multipartRequest.getFiles("filePath");
            size = fileList.size();
            if (size > 0) {
                //根据日期生成独立文件夹
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                //这里为什么不用日期格式化
                String dirName = year + "-" + (month < 10 ? "0" : "") + month + "-" + (day < 10 ? "0" : "") + day;

                for (int i = 0; i < size; i++) {
                    try {
                        MultipartFile file = fileList.get(i);
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        String originalName = file.getOriginalFilename();//原始文件名
                        String fileName = uuid + "_" + originalName;//修改上传文件名
                        String fileType = originalName.substring(originalName.lastIndexOf(".") + 1);//获取文件类型
                        urlList += "/" + dirName + "/" + fileName + ",";
                        InputStream ips = file.getInputStream();
                        FileUtils fileUtils = new FileUtils();

                        invoiceFile.setFileName(originalName);
                        invoiceFile.setUploadFileName(fileName);


                        //保存到本地
                        flag = fileUtils.copyFileContent(ips, fileName, photoPath + "/" + dirName);

                        //第一张缩略图,上传缩略图到服务器
                        if (i == 0) {
                            String substring = fileName.substring(0, fileName.lastIndexOf("."));
                            String thumbnailPath = "/" + dirName + "/" + substring + "_thumbnail." + fileType; //缩略图路径

                            File targetFile = new File(photoPath, thumbnailPath);
                            BufferedImage tempimage = Thumbnails.of(file.getInputStream()).scale(1).asBufferedImage();
                            int minboader = tempimage.getWidth() > tempimage.getHeight() ? tempimage.getHeight()
                                    : tempimage.getWidth();
                            Thumbnails.of(tempimage)
                                    .sourceRegion(Positions.CENTER, minboader, minboader)
                                    .size(600, 300)
                                    /*.outputFormat("jpg")*/
                                    .toFile(targetFile);

//                            //保存到本地
//                            OutputStream os = new FileOutputStream(photoPath + thumbnailPath);
//                            Thumbnails.of(file.getInputStream())
//                                    .width(600)
//                                    .sourceRegion(Positions.CENTER, minboader, minboader).size(600, 300)
//                                    .toOutputStream(os);

//                            invoiceFile.setThumbnail(thumbnailPath);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                urlList = urlList.substring(0, urlList.length() - 1);
//                invoiceFile.setUrlList(urlList);
                if (flag) {
                    result = service.insert(invoiceFile);
                }
            }
        }
        if (result)
            return new ResponseObj<>(invoiceFile.getFileId() + "", RetCode.SUCCESS);
        return new ResponseObj<>("", RetCode.FAIL);
    }

}

FileUtils

package com.cicdi.invoice.common.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.*;

/**
 * 文件操作工具类
 * 文件操作工具类,拷贝文件、目录;删除文件、目录等
 *
 * @createTime 2018/8/24下午3:21
 */
public class FileUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     */
    public static void copyFile(String oldPath, String newPath) {
        FileOutputStream fs = null;
        InputStream inStream = null;
        try {
            int bytesum = 0;
            int byteread;
            ClassPathResource classPathResource = new ClassPathResource(oldPath);
            inStream = classPathResource.getInputStream();
            File newfile = ResourceUtils.getFile(newPath);
            if (inStream != null) { //文件存在时
                fs = new FileOutputStream(newfile);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    LOGGER.debug("copy {} size", bytesum);
                    fs.write(buffer, 0, byteread);
                }
            }
        } catch (Exception e) {
            LOGGER.error("复制单个文件操作出错", e);
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(fs);
            org.apache.commons.io.IOUtils.closeQuietly(inStream);
        }

    }

    public static void copyFileContent(File fromFile, File toFile) throws IOException {
        FileInputStream ins = null;
        FileOutputStream out = null;
        try {
            ins = new FileInputStream(fromFile);
            out = new FileOutputStream(toFile);
            byte[] b = new byte[1024];
            int n;
            while ((n = ins.read(b)) != -1) {
                out.write(b, 0, n);
            }
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(ins);
            org.apache.commons.io.IOUtils.closeQuietly(out);
        }
    }

    /**
     * 复制文件内容
     *
     * @param inputStream 输入流
     * @param fileName    源文件名称
     * @param newPath     新文件所在路径
     * @return 成功or失败
     */
    public static boolean copyFileContent(InputStream inputStream, String fileName, String newPath) {
        boolean result = false;
        File file = new File(newPath);
        if (!file.exists()) {
            boolean b = file.mkdirs();
            if (!b) {
                LOGGER.error("mkdir {} failed", newPath);
                return false;
            }
        }

        newPath = newPath + "\\" + fileName;
        File toFile = new File(newPath);
        FileOutputStream out = null;

        try {
            out = new FileOutputStream(toFile);
            byte[] b = new byte[1024];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            result = true;
        } catch (FileNotFoundException e) {
            LOGGER.error("copy file but file not found", e);
        } catch (IOException e) {
            LOGGER.error("copy file but IOException", e);
        } finally {
            org.apache.commons.io.IOUtils.closeQuietly(inputStream);
            org.apache.commons.io.IOUtils.closeQuietly(out);
        }
        return result;
    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如:c:/fqf
     * @param newPath String 复制后路径 如:f:/fqf/ff
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            org.apache.commons.io.FileUtils.copyDirectory(new File(oldPath), new File(newPath));
        } catch (IOException e) {
            LOGGER.error("copy file from {} to {} exception", oldPath, newPath, e);
        }

        /*
        (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
        try {
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }
        */
    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的路径+文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String sPath) {
        File file = new File(sPath);
        if (!file.exists() || file.isDirectory()) {
            return false;
        }
        return org.apache.commons.io.FileUtils.deleteQuietly(new File(sPath));
    }

    /**
     * 删除目录(文件夹)以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }

        try {
            org.apache.commons.io.FileUtils.deleteDirectory(new File(sPath));
            return true;
        } catch (IOException e) {
            return false;
        }
        /*
        Boolean flag = true;
        // 删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } // 删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        // 删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
        */
    }

}

相关文章

网友评论

      本文标题:前端上传图片保存到本地静态资源路径下,再通过url获取

      本文链接:https://www.haomeiwen.com/subject/ybzuxqtx.html