欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實(shí)現(xiàn)文件上傳下載和圖片壓縮代碼示例

 更新時(shí)間:2015年03月12日 14:43:28   投稿:hebedich  
本文給大家介紹的是項(xiàng)目中經(jīng)常需要用到的一個(gè)常用的功能,使用java實(shí)現(xiàn)文件的上傳下載和圖片的壓縮功能,這里推薦給大家,有需要的小伙伴參考下。

分享一個(gè)在項(xiàng)目中用的到文件上傳下載和對(duì)圖片的壓縮,直接從項(xiàng)目中扒出來的:)

復(fù)制代碼 代碼如下:

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);
    /**
     * 上傳文件到服務(wù)器
     * @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 需要壓縮的長(zhǎng)度
     * @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對(duì)象 
                .asBufferedImage(); 
        //把內(nèi)存中的圖片寫入到指定的文件中 
        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 需要壓縮的長(zhǎng)度
     * @return
     * @throws IOException
     */
    public static String downloadThumbnailatorImage(String servicePath,String uri,int x,int y) throws IOException {
        //校驗(yàn)圖片是否存在
        String uriSubPath = uri.substring(0, uri.lastIndexOf("/")+1);//文件名以前,服務(wù)器以后
        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對(duì)象 
                    .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;
    }
}

以上就是本文分享的所有內(nèi)容了,希望對(duì)大家能有所幫助。

相關(guān)文章

  • Java實(shí)現(xiàn)的漢語拼音工具類完整實(shí)例

    Java實(shí)現(xiàn)的漢語拼音工具類完整實(shí)例

    這篇文章主要介紹了Java實(shí)現(xiàn)的漢語拼音工具類,結(jié)合完整實(shí)例形式分析了java基于pinyin4j包實(shí)現(xiàn)編碼轉(zhuǎn)換的相關(guān)操作技巧,需要的朋友可以參考下
    2017-11-11
  • JVM完全解讀之YGC來龍去脈分析

    JVM完全解讀之YGC來龍去脈分析

    YGC是JVM?GC當(dāng)前最為頻繁的一種GC,一個(gè)高并發(fā)的服務(wù)在運(yùn)行期間,會(huì)進(jìn)行大量的YGC,發(fā)生YGC時(shí),會(huì)進(jìn)行STW,一般時(shí)間都很短,除非碰到Y(jié)GC時(shí),存在大量的存活對(duì)象需要進(jìn)行拷貝
    2022-01-01
  • java響應(yīng)式編程之Reactor使用示例解析

    java響應(yīng)式編程之Reactor使用示例解析

    這篇文章主要為大家介紹了java響應(yīng)式編程之Reactor使用示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • SpringCloud如何解決服務(wù)之間的通信問題

    SpringCloud如何解決服務(wù)之間的通信問題

    本文主要介紹了SpringCloud如何解決服務(wù)之間的通信問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-08-08
  • MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的方法

    MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的方法

    動(dòng)態(tài)SQL是MyBatis強(qiáng)大特性之一,極大的簡(jiǎn)化我們拼裝SQL的操作,本文主要介紹了MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-06-06
  • Java?InheritableThreadLocal使用示例詳解

    Java?InheritableThreadLocal使用示例詳解

    InheritableThreadLocal繼承了ThreadLocal,此類擴(kuò)展了ThreadLocal以提供從父線程到子線程的值的繼承:當(dāng)創(chuàng)建子線程時(shí),子線程接收父線程具有的所有可繼承線程局部變量的初始值。?通常子線程的值與父線程的值是一致的
    2022-09-09
  • 淺談java反射和自定義注解的綜合應(yīng)用實(shí)例

    淺談java反射和自定義注解的綜合應(yīng)用實(shí)例

    本篇文章主要介紹了java反射和自定義注解的綜合應(yīng)用,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-09-09
  • Spring自定義注解實(shí)現(xiàn)數(shù)據(jù)脫敏

    Spring自定義注解實(shí)現(xiàn)數(shù)據(jù)脫敏

    在當(dāng)今數(shù)據(jù)安全越來越受到重視的背景下,許多企業(yè)都對(duì)敏感數(shù)據(jù)的保護(hù)有著嚴(yán)格的要求,本文就來深入探討一下如何自定義注解來實(shí)現(xiàn)對(duì)敏感數(shù)據(jù)的脫敏處理吧
    2024-11-11
  • Java工作隊(duì)列代碼詳解

    Java工作隊(duì)列代碼詳解

    這篇文章主要介紹了Java工作隊(duì)列代碼詳解,涉及Round-robin 轉(zhuǎn)發(fā),消息應(yīng)答(messageacknowledgments),消息持久化(Messagedurability)等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • java 基于maven多模塊合并打包部署的操作過程

    java 基于maven多模塊合并打包部署的操作過程

    這篇文章主要介紹了java 基于maven多模塊合并打包部署的操作過程,本文通過實(shí)例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02

最新評(píng)論