当前位置: 首页 > 编程笔记 >

java实现文件上传下载和图片压缩代码示例

丁勇
2023-03-14
本文向大家介绍java实现文件上传下载和图片压缩代码示例,包括了java实现文件上传下载和图片压缩代码示例的使用技巧和注意事项,需要的朋友参考一下

分享一个在项目中用的到文件上传下载和对图片的压缩,直接从项目中扒出来的:)


package com.eabax.plugin.yundada.utils;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

import java.util.UUID;

import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.json.JSONObject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.eabax.plugin.yundada.GaContext;

public class FileUploadDownloadUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUploadDownloadUtil.class);

    /**

     * 上传文件到服务器

     * @param request

     * @param type

     * @return

     * @throws Exception

     */

    public static String upload(HttpServletRequest request, String type) throws Exception {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        String saveFileName = null;

        if (isMultipart) {

            String savePath = request.getSession().getServletContext()

                    .getRealPath("/")

                    + "/upload/";

            String tempPath = request.getSession().getServletContext()

                    .getRealPath("/")

                    + "/upload/temp/";

            File saveFile = new File(savePath);

            File tempFile = new File(tempPath);

            if (!saveFile.isDirectory())

                saveFile.mkdirs();

            if (!tempFile.isDirectory())

                tempFile.mkdirs();

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(1024 * 4);

            factory.setRepository(tempFile);

            ServletFileUpload uploader = new ServletFileUpload(factory);

            uploader.setSizeMax(20 * 1024 * 1024);

            List<FileItem> fileItems = uploader.parseRequest(request);

            for (FileItem item : fileItems) {

                if (item.isFormField()) {

                    // funName=item.getString();

                } else {

                    // String fileName=item.getName();

                    // String

                    // fix=fileName.substring(fileName.lastIndexOf(".")+1);

                    String fix = type;

                    Date nowDate = new Date();

                    SimpleDateFormat sdf = new SimpleDateFormat(

                            "yyyyMMddhhmmss");

                    String fileName = sdf.format(nowDate);

                    fileName += System.currentTimeMillis();

                    fileName += "." + fix;

                    saveFileName = "/upload/" + fileName;

                    File file = new File(savePath + fileName);

                    item.write(file);

                }

            }

        }

        return saveFileName;

    }

    /**

     * 上传头像

     * @param request

     * @param type

     * @return

     * @throws Exception

     */

    public static String uploadHeadShow(HttpServletRequest request,GaContext context, String type) throws Exception {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        String saveFileName = null;

        String imagePath = "/upload/headshow/";

        String x = request.getParameter("length");

        String y = request.getParameter("wide");

        if (isMultipart) {

            String headShowServicePath = request.getSession().getServletContext()

                    .getRealPath("/")

                    + imagePath;

            Date nowDate = new Date();

            SimpleDateFormat sdf = new SimpleDateFormat(

                    "yyyyMMddhhmmss");

            String fileName = context.getUsername()+sdf.format(nowDate);

            File headShowFile = new File(headShowServicePath);

            if (!headShowFile.isDirectory())

                headShowFile.mkdirs();

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(1024 * 4);

            factory.setRepository(headShowFile);

            ServletFileUpload uploader = new ServletFileUpload(factory);

            uploader.setSizeMax(20 * 1024 * 1024);

            List<FileItem> fileItems = uploader.parseRequest(request);

            for (FileItem item : fileItems) {

                if (item.isFormField()) {

                    // funName=item.getString();

                } else {

                    String fix = type;

                    fileName += "." + fix;

                    saveFileName = imagePath + fileName;

                    File file = new File(headShowServicePath + fileName);

                    item.write(file);

                }

            }

            //压缩图片

            if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {

                saveFileName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));

            }

        }

        return saveFileName;

    }

    /**

     * 上传分享图片

     * @param request

     * @param type

     * @return

     * @throws Exception

     */

    public static JSONObject uploadArticleImage(HttpServletRequest request,GaContext context, String type) throws Exception {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        JSONObject saveFileName = new JSONObject();

        String imagePath = "";

        String x = request.getParameter("length");

        String y = request.getParameter("wide");

        if("4".equals(type)) {

            //分享上传图片路径

            imagePath = "/upload/articleimage/";

        }else if("5".equals(type)) {

            //链接上传图片路径

            imagePath = "/upload/linkimage/";

        } else {

            //头像上传图片路径

            imagePath = "/upload/headshow/";

        }

        if (isMultipart) {

            String headShowServicePath = request.getSession().getServletContext()

                    .getRealPath("/")

                    + imagePath;

            File headShowFile = new File(headShowServicePath);

            if (!headShowFile.isDirectory())

                headShowFile.mkdirs();

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(1024 * 4);

            factory.setRepository(headShowFile);

            ServletFileUpload uploader = new ServletFileUpload(factory);

            uploader.setSizeMax(20 * 1024 * 1024);

            List<FileItem> fileItems = uploader.parseRequest(request);

            for (FileItem item : fileItems) {

                UUID uuid = UUID.randomUUID();

                String fileName = uuid.toString();

                if (item.isFormField()) {

                    // funName=item.getString();

                } else {

                    String fix = type;

                    fileName += "." + fix;

                    saveFileName.put( uuid.toString(),imagePath + fileName);

                    File file = new File(headShowServicePath + fileName);

                    item.write(file);

                }

                //压缩图片

                if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {

                    String thumbnailatorName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));

                    saveFileName.put("thumbnailatorImage", thumbnailatorName);

                }

            }

        }

        return saveFileName;

    }

    /**

     * 上传压缩压缩并保存图片

     * @param oldSavePath 原文件路径

     * @param oldFileName 原文件名称

     * @param fix 文件类型

     * @param x 需要压缩的宽度

     * @param y 需要压缩的长度

     * @return

     * @throws IOException

     */

    public static String thumbnailatorImage(String oldSavePath,String oldFileName,String fix,int x,int y) throws IOException {

         //Thumbnail读取并压缩图片

        BufferedImage waterMarkBufferedImage = Thumbnails.of(oldSavePath+oldFileName)  

                //Thumbnail的方法,压缩图片

                .size(x, y)

                //读取成BufferedImage对象  

                .asBufferedImage();  

        //把内存中的图片写入到指定的文件中  

        String savePath = oldSavePath+x+"-"+y+"/";

        File saveFile = new File(savePath);

        if (!saveFile.isDirectory())

            saveFile.mkdirs();

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(1024 * 4);

        factory.setRepository(saveFile);

        ServletFileUpload uploader = new ServletFileUpload(factory);

        uploader.setSizeMax(20 * 1024 * 1024);

        UUID uuid = UUID.randomUUID();

        String fileName = uuid.toString();

        fileName += "." + fix;

        String saveFileName = savePath+fileName;

        File fileOutPut = new File(saveFileName);  

        ImageIO.write(waterMarkBufferedImage, fix, fileOutPut);

        return saveFileName;

    }

    /**

     * 下载压缩压缩并保存图片

     * @param oldSavePath 原文件路径

     * @param oldFileName 原文件名称

     * @param fix 文件类型

     * @param x 需要压缩的宽度

     * @param y 需要压缩的长度

     * @return

     * @throws IOException

     */

    public static String downloadThumbnailatorImage(String servicePath,String uri,int x,int y) throws IOException {

        //校验图片是否存在

        String uriSubPath = uri.substring(0, uri.lastIndexOf("/")+1);//文件名以前,服务器以后

        String fileName = uri.substring(uri.lastIndexOf("/")+1,uri.length());//文件名

        String getThumbnailatorPath = servicePath + uriSubPath+x+"-"+y+"/";

        String saveFileName = getThumbnailatorPath+fileName;

        File downFilePath = new File(getThumbnailatorPath);//压缩以后的文件夹

        File downFile = new File(saveFileName);//压缩以后的文件

        if (downFilePath.isDirectory()&&downFile.exists()) {

            return saveFileName;

        } else {

         //Thumbnail读取并压缩图片

            log.error(servicePath+uri);

            BufferedImage waterMarkBufferedImage = Thumbnails.of(servicePath+uri)  

                    //Thumbnail的方法,压缩图片

                    .size(x, y)

                    //读取成BufferedImage对象  

                    .asBufferedImage(); 

            if (!downFilePath.isDirectory()) {

                downFilePath.mkdirs();

            }

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(1024 * 4);

            factory.setRepository(downFilePath);

            ServletFileUpload uploader = new ServletFileUpload(factory);

            uploader.setSizeMax(20 * 1024 * 1024);

            File fileOutPut = new File(saveFileName);  

            ImageIO.write(waterMarkBufferedImage, "jpg", fileOutPut);

        }

        return saveFileName;

    }

}

以上就是本文分享的所有内容了,希望对大家能有所帮助。

 类似资料:
  • 本文向大家介绍java文件上传下载代码实例,包括了java文件上传下载代码实例的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java文件上传下载的具体代码,供大家参考,具体内容如下 文件上传 文件下载 以上所述是小编给大家介绍的java文件上传下载详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对呐喊教程网站的支持!

  • 本文向大家介绍php实现上传图片文件代码,包括了php实现上传图片文件代码的使用技巧和注意事项,需要的朋友参考一下 代码很简单,这里我们就不多废话了,直接奉上源码 以上所述就是本文的全部内容了,希望大家能够喜欢。

  • 本文向大家介绍java文件上传下载功能实现代码,包括了java文件上传下载功能实现代码的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了文件上传下载java实现代码,供大家参考,具体内容如下 前台: 1. 提交方式:post 2. 表单中有文件上传的表单项: <input type=”file” /> 3. 指定表单类型:     默认类型:enctype="application/x

  • 本文向大家介绍SpringMVC实现文件的上传和下载实例代码,包括了SpringMVC实现文件的上传和下载实例代码的使用技巧和注意事项,需要的朋友参考一下 前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:“用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流”。我回复他说:“使用SpringMVC框架可以做到这一点,因为SpringMVC为文件的上传提供了直接的支持,但需要

  • 本文向大家介绍iOS实现压缩图片上传功能,包括了iOS实现压缩图片上传功能的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了iOS实现压缩图片上传功能,供大家参考,具体内容如下 以上就是本文的全部内容,希望对大家学习iOS程序设计有所帮助。

  • 本文向大家介绍java web上传文件和下载文件代码片段分享,包括了java web上传文件和下载文件代码片段分享的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java web上传文件和下载文件的具体代码,供大家参考,具体内容如下 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。