首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java WebService 文件上傳下載完整實現(Base64 編碼)

     編輯:Java 相關知識

架構

服務端:接收 Base64 字符串 → 解碼 → 寫入磁盤 → 返回存儲路徑。
客戶端:讀取文件 → Base64 編碼 → 調用服務 → 下載時解碼保存。

服務端核心類 FileProgress

package com;

import javax.imageio.ImageIO;
import java.io.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Random;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class FileProgress {
    // 上傳
    public String uploadFile(String fileName, String fileType, String base64Data) {
        try {
            String dir = getDir(fileType);
            if (dir.isEmpty()) return "";
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64Data);

            String saveName = dateTimeStr(true) + new Random().nextInt(10000) 
                            + fileName.substring(fileName.lastIndexOf('.'));
            FileOutputStream fos = new FileOutputStream(dir + saveName);
            fos.write(bytes);
            fos.flush();
            fos.close();
            return dir + saveName;
        } catch (Exception e) { e.printStackTrace(); return ""; }
    }

    // 下載
    public String downloadFile(String filePath) {
        try (FileInputStream in = new FileInputStream(filePath)) {
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            return new BASE64Encoder().encode(bytes);
        } catch (Exception e) { e.printStackTrace(); return ""; }
    }

    // 目錄按類型/日期分層
    private String getDir(String type) {
        String base = "F:/youme/{0}/" + dateStr() + "/";
        String sub = "2".equals(type) ? "image" : "3".equals(type) ? "vedio" : "";
        if (sub.isEmpty()) return "";
        File dir = new File(base.replace("{0}", sub));
        return dir.mkdirs() || dir.exists() ? dir.getAbsolutePath() + "/" : "";
    }

    private String dateStr() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
    }
    private String dateTimeStr(boolean forFile) {
        return new SimpleDateFormat(forFile ? "yyyyMMddHHmmss" : "yyyy-MM-dd HH:mm:ss")
               .format(new Date(System.currentTimeMillis()));
    }
}

發布與測試步驟

  1. Eclipse 建立 Dynamic Web Project,放入類。
  2. 右鍵類 → Web Services → Create Web Service (Bottom-up)。
  3. 啟動 Tomcat,WSDL 自動生成。
  4. 右鍵 WSDL → Web Services → Test with Web Services Explorer,輸入 Base64 字符串測試。

關鍵點提示

  • 大文件建議分塊上傳或使用 MTOM/XOP,避免 Base64 體積膨脹 33%。
  • sun.misc.BASE64Encoder 為內部 API,生產建議用 java.util.Base64 (Java 8+)。
  • 路徑硬編碼需改為配置化。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved