package com.linvan.front;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.RandomAccess;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.linvan.util.TransUtil;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private File file;// 上傳的文件
private String fileFileName;// 上傳的文件名
private String fileContentType;// 上傳的文件類型
public String toUpload() {
return SUCCESS;
}
/**
* 上傳文件
*
* @return
*/
public String upload() {
if (!ServletActionContext.getRequest().getMethod().equals("POST")) {
return INPUT;
}
System.out.println(TransUtil.getSha1(file));
String realPath = ServletActionContext.getServletContext().getRealPath(
"/upload");
if (file != null) {
File saveFile = new File(new File(realPath), fileFileName);
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
// 若是文件已經存在,則開始續傳
if (saveFile.exists()) {
// 先得到已經保存的文件大小
long size = saveFile.length();
RandomAccessFile oSavedFile;//用它來保存文件
try {
oSavedFile = new RandomAccessFile(saveFile, "rw");//保存的文件:saveFile
InputStream in = new FileInputStream(file);//輸入流
try {
oSavedFile.seek(size);//跳過size長度開始保存文件
byte[] b = new byte[1024];
int nRead;
in.skip(size);//跳過size長度開始輸出文件file
while ((nRead = in.read(b, 0, 1024)) > 0) {
oSavedFile.write(b, 0, nRead);
}
System.out.println(TransUtil.getSha1(saveFile));//輸出saveFile的sha-1散列值
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
try {
FileUtils.copyFile(file, saveFile);
System.out.println(TransUtil.getSha1(saveFile));
} catch (IOException e) {
e.printStackTrace();
System.out.println("上傳文件失敗");
}
}
}
return SUCCESS;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
}
上面是上傳文件的Action,支持斷點續傳
獲取文件SHA-1 散列值 方法:
public static String getSha1(File file) {
try {
MessageDigest messagedigest = MessageDigest.getInstance("sha-1");
int len = 0;
byte[] buffer = new byte[1024 * 1024 * 10];
try {
FileInputStream in = new FileInputStream(file);
while ((len = in.read(buffer)) >0) {
//該對象經過使用 update()方法處理數據
messagedigest.update(buffer, 0, len);
}
in.close();
byte[] hash = messagedigest.digest();
return bytesToHexString(hash);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}