1. 程式人生 > >大文分片上傳 多執行緒上傳檔案(接收端)

大文分片上傳 多執行緒上傳檔案(接收端)

package com.controller;

import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.response.BaseResponse;

@Controller
public class ReceiveFileController {

	private static final Logger logger = Logger.getLogger(ReceiveFileController.class);
	@RequestMapping(value = "/receive/receivefile", method = RequestMethod.POST)
	/*
	 * 引數名稱與前面客戶端對應 multipartFile:傳到後臺的具體檔案 blockNumber:將檔案分成的總塊數
	 * blockIndex:這次請求的是第幾塊 targetFilePath:要根據這個路徑制定塊檔案的路徑和生成檔案的路徑
	 */
	@ResponseBody
	public BaseResponse fileUpload(
			HttpServletResponse response,
			@RequestParam(value = "blockIndex", required = false) String blockIndex,
			@RequestParam(value = "blockNumber", required = false) String blockNumber,
			@RequestParam(value = "targetFilePath", required = false) String targetFilePath,
			@RequestParam(value = "randomUUID", required = false) String randomUUID,
			@RequestParam(value = "file", required = false) MultipartFile multipartFile)
			 {
		// 檔案不走分塊上傳

		System.out.println(new Date());
		BaseResponse baseResponse = new BaseResponse();
		baseResponse.setCode(0);
		
		if (Integer.valueOf(blockNumber) == 1) {
			File destTempFile = new File(targetFilePath);
			File fileParent = destTempFile.getParentFile();
			if (!fileParent.exists()) {
				fileParent.mkdirs();
			}
			try {
				destTempFile.createNewFile();
				if (multipartFile == null) {
					baseResponse.setCode(0);
					return baseResponse;
				}
				DigestUtils.md5Hex(multipartFile.getInputStream());
				FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),
						destTempFile);
				baseResponse.setCode(1);
				return baseResponse;
			} catch (IOException e) {
				logger.error("檔案寫入異常",e);
				
				System.out.println("檔案寫入異常");
				e.printStackTrace();
			}
		} else if (Integer.valueOf(blockNumber) > 1) {
			
			try {
				String fileRealName = targetFilePath;
				String fileIndexPath = targetFilePath + ".index";
				targetFilePath = targetFilePath + ".part";
				File destTempFile = new File(targetFilePath);
				File fileParent = destTempFile.getParentFile();

				if (!fileParent.exists()) {
					fileParent.mkdirs();
				}
				try {
					destTempFile.createNewFile();
				} catch (IOException e) {
					System.out.println("新建目錄異常");
					e.printStackTrace();
				}
				
				fileConsistent(randomUUID,fileIndexPath,targetFilePath);
				byte[] buf = new byte[1024 * 1024 * 2];
				int len = 0;
				RandomAccessFile fileWrite = new RandomAccessFile(destTempFile,
						"rw");
				InputStream fileReader = multipartFile.getInputStream();
				fileWrite.seek((Integer.valueOf(blockIndex) - 1) * 104857600);
				while ((len = fileReader.read(buf)) != -1) {
					fileWrite.write(buf, 0, len);
				}
				fileReader.close();
				fileWrite.close();

				if (fileComplete(randomUUID, fileIndexPath,
						Integer.valueOf(blockIndex),
						Integer.valueOf(blockNumber))) {
					File file = new File(targetFilePath);
					file.renameTo(new File(fileRealName));
					baseResponse.setCode(1);
					return baseResponse;
				}

			} catch (IOException e) {
				System.out.println("part檔案寫入異常");
				logger.error("part檔案寫入異常",e);
				e.printStackTrace();
			}
		}
		return baseResponse;
	}
	public static boolean fileComplete(String randomUUID, String fileIndexPath,
			int index, int blockNumber) throws IOException {
		File fileIndex = new File(fileIndexPath);

		RandomAccessFile fileIndexWrite = new RandomAccessFile(fileIndex, "rw");

		fileIndexWrite.seek(randomUUID.length() + index * 4);
		String number = String.valueOf(index) + ",";
		fileIndexWrite.write(number.getBytes());
		fileIndexWrite.seek(randomUUID.length());
		byte[] buff = new byte[4];
		// 用於儲存實際讀取的位元組數
		int hasRead = 0;
		// 迴圈讀取
		String fileContent = "";
		while ((hasRead = fileIndexWrite.read(buff)) > 0) {
			fileContent = fileContent + new String(buff, 0, hasRead);
		}
		fileIndexWrite.close();
		String[] list = fileContent.split(",");
		System.out.println(list.length);
		if (list.length == blockNumber) {
			fileIndex.delete();
			return true;
		}
		return false;
	}

	public static void fileConsistent(String randomUUID, String fileIndexPath,
			String filepath) throws IOException {
		File fileIndex = new File(fileIndexPath);
		if (!fileIndex.exists()) {
			RandomAccessFile fileIndexWrite = new RandomAccessFile(fileIndex,
					"rw");
			fileIndexWrite.seek(0);
			fileIndexWrite.write(randomUUID.getBytes());
			fileIndexWrite.close();
		} else {
			RandomAccessFile fileIndexWrite = new RandomAccessFile(fileIndex,
					"rw");
			fileIndexWrite.seek(0);
			byte bys[] = new byte[36];
			fileIndexWrite.read(bys);
			String udil = new String(bys);
			fileIndexWrite.close();
			if (!udil.equals(randomUUID)) {
				fileIndex.delete();
				File file = new File(filepath);
				file.delete();
				RandomAccessFile fileIndexWriter = new RandomAccessFile(
						fileIndex, "rw");
				fileIndexWriter.seek(0);
				fileIndexWriter.write(randomUUID.getBytes());
				fileIndexWriter.close();
			}
			
		}
		
	}
 
}