ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

后端文件上传(图片)

2022-04-03 12:04:41  阅读:115  来源: 互联网

标签:文件 String name File new 上传 final append 图片


后台接口代码

上传

import com.wuxiapptec.uniteplatform.rest.modular.domain.util.Encodes;
import com.wuxiapptec.uniteplatform.rest.modular.domain.util.Digests;

private static final String FILE_SEPARATOR = "/";

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<?> upload(@RequestPart("file") MultipartFile file) throws IOException {
        log4.info("上传文件");
        Map<String, String> result = new HashMap<>();
        if (file.isEmpty()) {
            log4.info("上传文件为空!");
            result.put("msg","上传文件不能为空");
            return new ResponseEntity<>(result, HttpStatus.NO_CONTENT);
        }
        String url = "";
        try {
            byte[] fileBytes = null;
            try {
                fileBytes = file.getBytes();
            } catch (final IOException e1) {
                e1.printStackTrace();
            }
            final String name = file.getOriginalFilename();
            final String md5 = Encodes.encodeHex(Digests.md5(fileBytes));
            StringBuilder path = getPath(md5);
            path = path.append(name);
            // 获取服务器文件资源保存路径(保存在数据库中)
            String serverFileSavePath = settingMapper.getSetValue("FileSavePath");;
            if (StringUtils.isEmpty(serverFileSavePath)) {
                result.put("msg","服务器文件保存路径为空");
                return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            String filePath = serverFileSavePath + FILE_SEPARATOR + path.toString();

            File localFile = null;
            try {
                localFile = new File(filePath);
                localFile.getParentFile().mkdirs();
                Files.write(fileBytes,localFile);
            } catch (final IOException e) {
                log4.error("保存文件失败: {}", e);
            }
            url = fileSavePath + FILE_SEPARATOR + md5 + FILE_SEPARATOR + name;
            // 缩略图名称添加固定后缀
            int i = name.lastIndexOf(".");
            String newName = name.substring(0,i) + "_thumbnail" + name.substring(i);
            String path2 = serverFileSavePath + FILE_SEPARATOR + getPath(md5).toString() + newName;
            // 按照一定比例生成缩略图
Thumbnails.of(localFile).scale(0.04f).outputQuality(1.0f).toFile(path2);
            String zoomOutUrl = fileSavePath + FILE_SEPARATOR + md5 + FILE_SEPARATOR + newName;
            // 返回原图和缩略图的url请求路径
            result.put("url",url);
            result.put("smallUrl",zoomOutUrl);
        } catch (final Exception e){
            log4.error("保存文件失败: {}", e);
            new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     * 获取上传文件的路径
     * @param md5
     * @return
     */
    private StringBuilder getPath(String md5) {
        final StringBuilder sb = new StringBuilder();
        // @formatter:off
        sb.append(StringUtils.left(md5, 2))
                .append(FILE_SEPARATOR)
                .append(StringUtils.mid(md5, 2, 2))
                .append(FILE_SEPARATOR)
                .append(md5)
                .append(FILE_SEPARATOR);
        // @formatter:off
        return sb;
    }

下载

import java.net.URLEncoder;
/**
     * 获取文件
     *
     * @param p
     * @param name
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/{p}/{name:.+}", method = RequestMethod.GET)
    public void download(@PathVariable("p") String p, @PathVariable("name") String name, HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        log4.info("文件资源获取");
        // get absolute path of the application
        final ServletContext context = request.getServletContext();
        final String appPath = context.getRealPath("");
        System.out.println("appPath = " + appPath);

        // construct the complete absolute path of the file
        final String fullPath = p + "/" + name;
        // 调用service解析请求路径获取对应文件
        final File downloadFile = fileService.downloadFile(fullPath);
        final FileInputStream inputStream = new FileInputStream(downloadFile);

        // get MIME type of the file
        String mimeType = context.getMimeType(fullPath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        final String headerKey = "Content-Disposition";
        String fileName = URLEncoder.encode(downloadFile.getName(),"UTF-8");
        final String headerValue = String.format("attachment; filename=\"%s\"",
                fileName);
        response.setHeader(headerKey, headerValue);

        // get output stream of the response
        final OutputStream outStream = response.getOutputStream();

        IOUtils.copy(inputStream, outStream);

        inputStream.close();
        outStream.close();

    }

service解析路径

import org.apache.commons.lang3.time.DateUtils;

    private static String[] parsePatterns = {"yyyy-MM-dd","yyyy年MM月dd日",
            "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
            "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd","yyyyMMddHHmmss"};

/**
     * 下载文件
     * @param path
     * @return
     * @throws IOException
     */
    public File downloadFile(String path) throws IOException {

        final String[] paths = path.split("/");
        final String p3 = paths[0];
        final String name = paths[1];
        final String p1 = StringUtils.left(p3, 2);
        final String p2 = StringUtils.mid(p3, 2, 2);
        // 获取服务器文件资源保存路径
        String fileSavePath = "";
        StringBuilder sb;
        try {
        // 根据不同的业务情况解析路径,获取文件的保存路径
            if (p3.contains("-")) {
                String[] tempPath = p3.split("-");
                fileSavePath = settingMapper.getSetValue("ImportModule");
                sb = new StringBuilder(fileSavePath).append(File.separator).append(tempPath[0]).append(File.separator)
                        .append(tempPath[1]).append(File.separator).append(name);
            } else {
                // 如果是日期格式则是excel
                DateUtils.parseDate(p3, parsePatterns);
                fileSavePath = settingMapper.getSetValue("ExcelSavePath");
                sb = new StringBuilder(fileSavePath).append(File.separator).append(p3).append(File.separator).append(name);
            }
        } catch (ParseException e) {
            fileSavePath = settingMapper.getSetValue("FileSavePath");
            sb = new StringBuilder(fileSavePath).append(File.separator).append(p1).append(File.separator).append(p2)
                    .append(File.separator).append(p3).append(File.separator).append(name);
        }

        final File file = new File(sb.toString());
        return file;
    }

ps:上述方法为当前业务案例,根据文件上传时的保存路径及返回的url,在下载时实现对应的解析,此处仍需完善

标签:文件,String,name,File,new,上传,final,append,图片
来源: https://www.cnblogs.com/wywblogs/p/16095487.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有