ajax上傳檔案,spring mvc獲取檔案並處理,通過頁面按鈕傳送url,由後臺控制檔案下載

Walter Sun發表於2018-04-29

前端頁面程式碼:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>加密與解密</title>
		<link rel="stylesheet" href="css/bootstrap.min.css" />
		<link rel="stylesheet" href="css/encrypt.css" />
		<script type="text/javascript" src="js/encrypt.js" ></script>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
	</head>

	<body>
	    <form class="inpform" id="uploadForm" enctype="multipart/form-data">
		<div class="col-lg-6">
			<div class="input-group input-center">
				<input id="t1" type="text" class="form-control" placeholder="請選擇需要加密的檔案">
				<span class="input-group-btn">
					<input type="file" id="file" name="mpfile" onchange="getFilePath()" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;"/>   
        			<button id="bj1" class="btn btn-default" type="button" onclick="selectFile();">請選擇</button>
      			</span>
			</div>
			<div class="input-group input-center">
				<input id="t2" name="key" type="password" class="form-control" placeholder="請選輸入金鑰(或隨機生成)">
				<span class="input-group-btn">
        			<button id="bj2" class="btn btn-default" type="button" onclick="KeyRandom()">隨機生成</button>
      			</span>
			</div>
			<div class="radio"> 
                <label class="radio-inline">
                    <input type="radio" name="optionsRadiosinline" id="optionsRadios1" value="1" checked> 加密
                </label>
                <label class="radio-inline">
                        <input type="radio" name="optionsRadiosinline" id="optionsRadios2"  value="2"> 解密
                </label>
            </div>
            <div class="radio"> 
                <label class="radio-inline">
                    <input type="radio" name="optionsRadiosinline2" id="optionsRadios3" value="3" checked> ECB模式
                </label>
                <label class="radio-inline">
                        <input type="radio" name="optionsRadiosinline2" id="optionsRadios4"  value="4"> CBC模式
                </label>
            </div>
            <div class="radio"> 
                <label class="radio-inline">
                    <input type="radio" name="optionsRadiosinline3" id="optionsRadios5" value="5" checked> 操作後上傳
                </label>
                <label class="radio-inline">
                    <input type="radio" name="optionsRadiosinline3" id="optionsRadios6"  value="6"> 操作後下載
                </label>
            </div>
			<div class="button">
                <button id="btn1" type="button" class="btn btn-primary" onclick="Save()">上傳</button>
            </div>
            <div class="button">
                <span>請先上傳檔案再下載!</span>
            </div>
            <div class="button">
                <button id="btn2" type="button" class="btn btn-primary" onclick="DownLoad()">下載</button>
            </div>
		</div>
		  </form>
	</body>

</html>

spring mvc 後臺程式碼:

package com.cczu.sm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cczu.sm.entity.SM3Digest;
import com.cczu.sm.entity.SM4;
import com.cczu.sm.entity.SM4Utils;
import com.cczu.sm.entity.SM4_Context;
import com.cczu.sm.entity.Util;

@Controller
public class SmController {
    @RequestMapping("/sm")
    @ResponseBody
    public void getFile(String optionsRadiosinline3,
            String optionsRadiosinline2, String optionsRadiosinline,
            String key, MultipartFile mpfile) throws Exception {
        String filename = mpfile.getOriginalFilename();
        String mykey = key;
        String myoption = optionsRadiosinline;
        System.out.println("金鑰:" + mykey + "\n" + "檔名:" + filename + "\n"
                + "功能選擇:" + myoption);

        byte[] input = mpfile.getBytes();

        //SM3雜湊金鑰
        byte[] md = new byte[32];
        byte[] msg1 = mykey.getBytes();
        SM3Digest sm3 = new SM3Digest();
        sm3.update(msg1, 0, msg1.length);
        sm3.doFinal(md, 0);
        String s = new String(Hex.encode(md)).substring(0, 16).toUpperCase();
        //        System.out.println("雜湊金鑰:" + s);

        //SM4加密
        //optionsRadiosinline等於1加密,等於2解密
        //optionsRadiosinline2等於3ECB模式,等於4CBC模式
        if (optionsRadiosinline.equals("1")) {
            //SM4設定加密金鑰
            SM4 s4 = new SM4();
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;
            byte[] keyBytes = s.getBytes();
            s4.sm4_setkey_enc(ctx, keyBytes);
            if (optionsRadiosinline2.equals("3")) {
                //ECB模式
                String path = "";
                //等於5上傳儲存伺服器,等於6上傳操作後下載
                if (optionsRadiosinline3.equals("5")) {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfile\\";
                } else {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfiledown\\";
                }
                File file = new File(path + filename + ".encecb");
                if (file.exists()) {
                    file.delete();
                    file.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(file);
                out.write(s4.sm4_crypt_ecb(ctx, input), 0,
                    s4.sm4_crypt_ecb(ctx, input).length);
                out.close();
            } else {
                //CBC模式
                String path = "";
                if (optionsRadiosinline3.equals("5")) {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfile\\";
                } else {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfiledown\\";
                }
                File file = new File(path + filename + ".enccbc");
                FileOutputStream out = new FileOutputStream(file);
                out.write(s4.sm4_crypt_cbc(ctx, keyBytes, input), 0,
                    s4.sm4_crypt_cbc(ctx, keyBytes, input).length);
                out.close();
            }
        } else {
            //解密操作
            //SM4設定加密金鑰
            SM4 s4 = new SM4();
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;
            byte[] keyBytes = s.getBytes();
            s4.sm4_setkey_dec(ctx, keyBytes);
            if (optionsRadiosinline2.equals("3")) {
                //ECB模式
                String path = "";
                //等於5上傳儲存伺服器,等於6上傳操作後下載
                if (optionsRadiosinline3.equals("5")) {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfile\\";
                } else {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfiledown\\";
                }
                File file = new File(path
                        + filename.substring(0, filename.lastIndexOf(".")));
                if (file.exists()) {
                    file.delete();
                    file.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(file);
                out.write(s4.sm4_crypt_ecb(ctx, input), 0,
                    s4.sm4_crypt_ecb(ctx, input).length);
                out.close();
            } else {
                //CBC模式
                String path = "";
                if (optionsRadiosinline3.equals("5")) {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfile\\";
                } else {
                    path = "F:\\MyEclipse 9Workspaces\\sm\\smfiledown\\";
                }
                File file = new File(path
                        + filename.substring(0, filename.lastIndexOf(".")));
                FileOutputStream out = new FileOutputStream(file);
                out.write(s4.sm4_crypt_cbc(ctx, keyBytes, input), 0,
                    s4.sm4_crypt_cbc(ctx, keyBytes, input).length);
                out.close();
            }
        }

    }

   
    @RequestMapping("/sm/download")
    public void downLoad(String file, HttpServletRequest request,
            HttpServletResponse response) {
        String path = "F:\\MyEclipse 9Workspaces\\sm\\smfiledown\\";
        File ofile = new File(path);
        for (File p : ofile.listFiles()) {
            if (!p.isDirectory()) {
                String fname = p.getName();
                FileInputStream fs = null;
                if (p.exists()) {
                    // response.setContentType("application/force-download");
                    try {
                        response.setHeader(
                            "Content-Disposition",
                            "attachment;fileName="
                                    + new String(fname.getBytes("utf-8"),
                                            "iso_8859_1"));
                        fs = new FileInputStream(p);
                        byte[] buf = new byte[1024];
                        int len = 0;
                        ServletOutputStream o = response.getOutputStream();
                        while ((len = fs.read(buf)) != -1) {
                            o.write(buf, 0, len);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("error", " 쳣  ");
                    } finally {
                        try {
                            if (fs != null)
                                fs.close();
                        } catch (IOException e) {
                            request.setAttribute("error", " 쳣  ");
                        }
                    }
                   p.delete();
                    break;
                }
            }
        }
    }

}


相關文章