Java 檔案上傳

來源:互聯網
上載者:User

標籤:ima   dig   www.   實體類   get   last   names   test   har   

1.pom.xml百度

2.核心:

2.1實體類 FileUploadDataBucket:

package com.dzpykj.files;import java.io.File;/** * 上傳檔案暫存資料的桶 * @author ChaiXY */public class FileUploadDataBucket {    /**即將要儲存的檔案*/    public File desFile;    /**源檔案*/    public File srcFile;    /**源檔案名稱(帶尾碼)*/    public String srcFileName;    /**儲存檔案的名稱(帶尾碼)*/    public String desFileName;    /**檔案類型*/    public String suffixName;    /**基礎路徑*/    public String basePath;    /**針對不同功能存放檔案可能有不同的檔案夾,或者同一模組不同檔案類型要存在不同的檔案夾,都會在基礎路徑下建立檔案夾,此欄位用於存放基礎路徑後的各自的路徑*/    public String ownPath;    /**資料存放區的存放路徑*/    public String dbFilePath;    /**檔案大小*/    public String fileSize;    /**檔案md5*/    public String contentMD5;            public File getDesFile() {        return desFile;    }    public void setDesFile(File desFile) {        this.desFile = desFile;    }    public File getSrcFile() {        return srcFile;    }    public void setSrcFile(File srcFile) {        this.srcFile = srcFile;    }    public String getSrcFileName() {        return srcFileName;    }    public void setSrcFileName(String srcFileName) {        this.srcFileName = srcFileName;    }    public String getDesFileName() {        return desFileName;    }    public void setDesFileName(String desFileName) {        this.desFileName = desFileName;    }    public String getSuffixName() {        return suffixName;    }    public void setSuffixName(String suffixName) {        this.suffixName = suffixName;    }    public String getBasePath() {        return basePath;    }    public void setBasePath(String basePath) {        this.basePath = basePath;    }    public String getOwnPath() {        return ownPath;    }    public void setOwnPath(String ownPath) {        this.ownPath = ownPath;    }    public String getDbFilePath() {        return dbFilePath;    }    public void setDbFilePath(String dbFilePath) {        this.dbFilePath = dbFilePath;    }    public String getFileSize() {        return fileSize;    }    public void setFileSize(String fileSize) {        this.fileSize = fileSize;    }    public String getContentMD5() {        return contentMD5;    }    public void setContentMD5(String contentMD5) {        this.contentMD5 = contentMD5;    }    }

 

2.2上傳檔案工具類FileUploadUtils:

package com.dzpykj.files;import java.io.File;import java.io.IOException;import java.math.BigDecimal;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Random;import javax.servlet.http.HttpServletRequest;import org.apache.commons.codec.digest.DigestUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.multipart.commons.CommonsMultipartResolver;/** * 檔案上傳 * @author ChaiXY */public class FileUploadUtils {        /**     * 上傳檔案,並且回傳資料桶(儲存要儲存到資料庫的資料)     * @param request      * @param basePath 基礎路徑(前後不要攜帶分隔字元,工具類會自動補全)     * @param ownPath 針對不同功能存放檔案可能有不同的檔案夾,或者同一模組不同檔案類型要存在不同的檔案夾,都會在基礎路徑下建立檔案夾,此欄位用於存放基礎路徑後的各自的路徑(前後不要攜帶分隔字元,工具類會自動補全)     * @return 資料桶     */    public static List<FileUploadDataBucket> uploadFiles(HttpServletRequest request, String basePath, String ownPath) throws IOException {        // 建立一個通用的多部分解析器        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());        List<FileUploadDataBucket> dataBuckets = new ArrayList<>();        // 判斷 request 是否有檔案上傳,即多部分請求        if (multipartResolver.isMultipart(request)) {            // 轉換成多部分request            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;            // 取得request中的所有檔案名稱            Iterator<String> iter = multiRequest.getFileNames();            while (iter.hasNext()) {                List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next());                                for(MultipartFile multipartFile:multipartFiles){                    String srcFileName = multipartFile.getOriginalFilename();// 原名稱 帶尾碼                    String suffixName = srcFileName.substring(srcFileName.lastIndexOf(".") + 1);// 檔案類型                    String contentMD5 = DigestUtils.md5Hex(multipartFile.getBytes());                    double size = (multipartFile.getSize() * 1.0) / (1024 * 1.0) / (1024 * 1.0);                    BigDecimal bg = new BigDecimal(size);                    double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();                    String fileSize = f1 + "";                                        String desFileName = generateFileName() + "." + suffixName;                    String dbFilePath = ownPath + File.separator + desFileName;                    String desFilePath = basePath + File.separator + dbFilePath;                                        File desFile = new File(desFilePath);                    if (!desFile.exists()) {                        desFile.mkdirs();                    }                                        if (StringUtils.isNotBlank(srcFileName)) {                        multipartFile.transferTo(desFile);                        FileUploadDataBucket fudb = new FileUploadDataBucket();                        fudb.setBasePath(basePath);                        fudb.setContentMD5(contentMD5);                        fudb.setDbFilePath(dbFilePath);                        fudb.setDesFile(desFile);                        fudb.setDesFileName(desFileName);                        fudb.setFileSize(fileSize);                        fudb.setOwnPath(ownPath);                        fudb.setSrcFileName(srcFileName);                        fudb.setSuffixName(suffixName);                        dataBuckets.add(fudb);                    }                }            }        }        return dataBuckets;    }        private static String generateFileName(){        String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());        long timeMillis = System.currentTimeMillis();        int random = new Random().nextInt(90)+10;        return dateStr+timeMillis+random;    }}

 

 

2.3設定檔

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="maxUploadSize">            <value>104857600</value>        </property>        <property name="maxInMemorySize">            <value>4096</value>        </property>        <property name="defaultEncoding">            <value>utf-8</value>        </property>        <!-- <property name="defaultEncoding" value="UTF-8" /> -->    </bean>

 

 

 3.簡單的測試

3.1Controller層FileUploadTestController:

package com.dzpykj.files.upload;import java.io.IOException;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.dzpykj.files.FileUploadDataBucket;import com.dzpykj.files.FileUploadUtils;import com.fasterxml.jackson.databind.ObjectMapper;@Controllerpublic class FileUploadTestController {        @RequestMapping("/fileUpload")    @ResponseBody    public String upload(HttpServletRequest req) throws IOException{        List<FileUploadDataBucket> dataBuckets = FileUploadUtils.uploadFiles(req,"E:\\fiels","pic");        String jsonStr = new ObjectMapper().writeValueAsString(dataBuckets).toString();        System.out.println(jsonStr);        return jsonStr;    }    }

 

 

3.2簡單jsp頁面 fileUpload.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>    <form action="/fileUpload" method="post" enctype="multipart/form-data">        <input type="file" name="fiel1" />         <br>        <input type="file" name="fiel2" />        <br>        <input type="submit" value="上傳檔案" />    </form></body></html>

 

Java 檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.