一、对方传过来文件名和文件流信息,皆为string类型,首先保存到本地文件,文件会保存在环境下的TempFile文件夹下(本案例是264X单据上传附件接口案例)
先将string类型的文件流转成byte[]类型:
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;//导包
byte[] bs = Base64.decode(filestr.trim());
/**
* 保存临时文件
*
* @param fileName 文件名
* @param bs 文件流
* @return 返回文件保存的路径
*/
public String SaveTempFile(String fileName, byte[] bs) {
FileOutputStream out = null;
String filepath = RuntimeEnv.getNCHome() + "\\TempFile\\" + fileName;
try {
File file = new File(filepath);
out = new FileOutputStream(file);
try {
out.write(bs,0,bs.length);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return filepath;
}
二、将本地文件上传
/**
* 文件上传
* @param parentPath 单据主键pk_jkbx
* @param newFile 文件路径
* @param filename 文件名
* @param user_code 创建人
* @return 0表示上传成功,-1表示失败
*/
public int Upload(String parentPath, String filepath, String filename,String user_code) {
QueryFile(parentPath, filename);
File file = new File(filepath);
Long fileLen = file.length();
String creator = user_code;
NCFileNode node = null;
InputStream fileinput = null;
try {
fileinput = new FileInputStream(file);
IFileSystemService service = (IFileSystemService) NCLocator
.getInstance().lookup(IFileSystemService.class);
node = service.createNewFileNodeWithStream(parentPath, filename,
creator, fileinput, fileLen);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (BusinessException e) {
e.printStackTrace();
} finally {
try {
fileinput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (node == null) {
return -1;
}
return 0;
}
/**
* 防止重复上传相同名称的附件
*
* @param parentPath
* 单据主键
* @param filename
* 文件名
*/
public void QueryFile(String parentPath, String filename) {
try {
String path = parentPath + "/" + filename;
BaseDAO dao = new BaseDAO();
String sql = "select filepath from sm_pub_filesystem where filepath = '"
+ path + "'";
List<Object[]> filelist = (List<Object[]>) dao.executeQuery(sql,
new ArrayListProcessor());
if (filelist != null && filelist.size() > 0) {// 如果有附件,则先删除
IFileSystemService service = (IFileSystemService) NCLocator
.getInstance().lookup(IFileSystemService.class);
String[] arg = new String[] { path };
service.deleteNCFileNodes(arg);
}
} catch (DAOException e) {
Logger.debug(e.getMessage());
e.printStackTrace();
} catch (BusinessException e) {
Logger.debug(e.getMessage());
e.printStackTrace();
}
}
三、上传成功之后删除本地保存的临时文件
File file = new File(filepath);
file.delete();// 文件上传结束后删除本地文件
四、注意
BaseDAO dao = new BaseDAO();
这个方法获取的是当前的数据源,如果没有设置数据源名称的话默认是design,也可以通过new BaseDao(“xxx”),xxx就是sysconfig下配置的数据源名称