java 上传文件 md5_Java实现文本文件MD5加密并ftp上传到远程主机

以下是JSP界面的源码:

业务类型

集团预出账

集团正式出账

接口月份:

formatFlag="date6" showDefault="true" cssClass="required validate-datetime">

选择文件

function importHandle() {

var fileName = $('upload').value;

if (fileName == null || fileName == undefined || fileName == "") {

validation.userDefined("请选择要上传的文件");

return;

}

fileName = fileName.split(".");

if (fileName[fileName.length - 1] == "txt" || fileName[fileName.length - 1] == "TXT") {

document.forms[0].action = "interfaceupload_UPLOAD_interfaceupload.do";

document.forms[0].submit();

} else {

validation.userDefined("文件格式错误,您上传的格式不被允许");

return;

}

}

二、点击上传按钮之后的函数为:importHandle(),提交的请求为interfaceupload_UPLOAD_interfaceupload.do

系统是由struts2实现的,因此要在配置中加入这一段请求相对应的action的配置

class="aicu.application.mps.voice.international.web.revenue.FileImportAction">

/WEB-INF/jsp/revenue/interfaceupload.jsp

interfaceupload

三、做好了相对应的准备工作,继续来写接下来的业务逻辑。

编写aicu.application.mps.voice.international.web.revenue.FileImportAction类

package aicu.application.mps.voice.international.web.revenue;

import aicu.application.mps.voice.international.web.revenue.FileUploadAction;

public class FileImportAction extends FileUploadAction {

public String execute() throws Exception {

System.out.println("hello");

smartUpload();

return SUCCESS;

}

}

由于FileImportAction继承了FileUploadAction,所以相对应的请求都会由>FileUploadAction的execute()来处理。

首先是获取上传上来的文件对象,通过声明上传文件的对象,内容类型,文件名,服务ID,然后在生成set()方法和get()方法便能获取到文件对象。

protected File upload;// 实际上传文件

protected String uploadContentType; // 文件的内容类型

protected String uploadFileName; // 上传文件名

protected String uploadServiceId;//上传服务ID

public File getUpload() {

return upload;

}

public void setUpload(File upload) {

this.upload = upload;

}

public String getUploadContentType() {

return uploadContentType;

}

public void setUploadContentType(String uploadContentType) {

this.uploadContentType = uploadContentType;

}

public String getUploadFileName() {

return uploadFileName;

}

public void setUploadFileName(String uploadFileName) {

this.uploadFileName = uploadFileName;

}

public String getUploadServiceId() {

return uploadServiceId;

}

public void setUploadServiceId(String uploadServiceId) {

this.uploadServiceId = uploadServiceId;

}

然后是对当前的文本文件进行MD5加密,生成同名的MD5文件,文件中只有一行加密之后的MD5字符串。

由于通过struts上传的文件是存放在临时目录下,我处理的思路是,先把文件copy到指定的路径下

String datapath = getRealPath()+"upload"+File.separator+UUID.randomUUID()+File.separator;

File newFile=new File(new File(datapath),uploadFileName);

if (!newFile.getParentFile().exists())

newFile.getParentFile().mkdirs();

FileUtils.copyFile(upload, newFile);

然后是生成MD5同名文件

FileMD5 filemd5=new FileMD5();

String md5str=filemd5.getMD5(newFile);

实现的思路是调用byteToHexString方法得到加密之后MD5的字符串,通过writeFileContent实现把文本写入同名的MD5文件中。FileMD5类的getMD5(File file)方法:

public String getMD5(File file) {

Boolean bool = false;

FileInputStream fis = null;

String filename=file.getName();

String[] newfilepath=filename.split("\\.");

String filenameTemp = file.getParent()+file.separator+newfilepath[0]+ ".md5";

File md5file = new File(filenameTemp);

try {

MessageDigest md = MessageDigest.getInstance("MD5");

fis = new FileInputStream(file);

byte[] buffer = new byte[2048];

int length = -1;

long s = System.currentTimeMillis();

while ((length = fis.read(buffer)) != -1) {

md.update(buffer, 0, length);

}

byte[] b = md.digest();

String filecontent=byteToHexString(b);

if (!md5file.exists()) {

md5file.createNewFile();

bool = true;

System.out.println("success create file,the file is "

+ md5file.getName());

writeFileContent(filenameTemp, filecontent);

}

else {

md5file.delete();

System.out.println("success delete file,the file is "

+ md5file.getName());

md5file.createNewFile();

bool = true;

System.out.println("success create file,the file is "

+ md5file.getName());

writeFileContent(filenameTemp, filecontent);

}

return byteToHexString(b);

} catch (Exception ex) {

ex.printStackTrace();

return null;

} finally {

try {

fis.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

byteToHexString方法,主要是实现对文本文件的MD5加密,得到加密之后的MD5文件

private String byteToHexString(byte[] tmp) {

String s;

char str[] = new char[16 * 2];

int k = 0;

for (int i = 0; i < 16; i++) {

byte byte0 = tmp[i];

str[k++] = hexdigits[byte0 >>> 4 & 0xf];

str[k++] = hexdigits[byte0 & 0xf];

}

s = new String(str);

return s;

}

writeFileContent方法,实现把文本写入同名的MD5文件中

public boolean writeFileContent(String filepath, String newstr) throws IOException {

Boolean bool = false;

//String filein = newstr + "\r\n";

String filein = new String(newstr);

String temp = "";

FileInputStream fis = null;

InputStreamReader isr = null;

BufferedReader br = null;

FileOutputStream fos = null;

PrintWriter pw = null;

try {

File file = new File(filepath);

fis = new FileInputStream(file);

isr = new InputStreamReader(fis);

br = new BufferedReader(isr);

StringBuffer buffer = new StringBuffer();

for (int i = 0; (temp = br.readLine()) != null; i++) {

buffer.append(temp);

buffer = buffer.append(System.getProperty("line.separator"));

}

buffer.append(filein);

fos = new FileOutputStream(file);

pw = new PrintWriter(fos);

pw.write(buffer.toString().toCharArray());

pw.flush();

bool = true;

} catch (Exception e) {

e.printStackTrace();

} finally {

if (pw != null) {

pw.close();

}

if (fos != null) {

fos.close();

}

if (br != null) {

br.close();

}

if (isr != null) {

isr.close();

}

if (fis != null) {

fis.close();

}

}

return bool;

}

四、获取到文本文件和生成同名的文件名之后,紧接着就是获取相对应的ftp主机,用户名,密码以及路径信息了。我把这相对应的信息保存在数据库中。首先我们把获取到的业务类型放入一个HashMap中。

parameterMap=new HashMap();

parameterMap.put("audit_flag",OperationType);

然后我们配置ibaits的sqlid

select ftphost, proguser, progpass, remotedirectory from t_ftp_config s

where 1 = 1

s.audit_flag = #audit_flag#

]]>

然后执行该sqlid的查询,把结果放入List 中

List resultType=EasyDataFatcherOnIbatis.queryBySqlKey("checkFtpType",false,parameterMap);

下面是根据该sqlid查询出来的List结果中,取出相关的信息

String host = (String)resultType.get(0).get("FTPHOST");

String user = (String)resultType.get(0).get("PROGUSER");

String pass = (String)resultType.get(0).get("PROGPASS");

String path = (String)resultType.get(0).get("REMOTEDIRECTORY");

//每月会自动生成一个月份的子目录

String relpath=path+rpmonth+"/";

至此,便可以获取到相对应的ftp主机,用户名,密码以及路径信息了。

五、最后一步是实现上传,我是用的FTPClient来实现的。

实现的操作都写在了FtpBBSUtil的FtpSento方法中,其中datapath表示需要传送文件的目录。

FtpBBSUtil.getFtpBBS().FtpSento(datapath, host, user, pass, relpath);

FtpBBSUtil的FtpSento方法如下所示:

public void FtpSento(String localPath, String host, String user,

String pass, String path) throws Exception {

login(host, 21, user, pass);

File parentFile = new File(localPath);

File[] files = parentFile.listFiles();

String outPath = path;

for (File aFile : files) {

if (aFile != null && aFile.getName() != null) {

put(aFile, outPath, new String((aFile.getName())

.getBytes("GB18030"), "ISO8859-1"));

}

}

logout();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值