概要
需要开发一个专门用来上传文件的组件图档功能,主要是用来上传各个工单的附件,上传到服务器ftp上。
需求
- 附件目录用excle维护,主要是维护附件名称和唯一编码和关联的业务编码,更新业务记录。
- 上传的附件打包成zip格式。
- 在ftp服务器上生成目录,存放上传的文件。
功能
使用commons-fileupload-1.3.1.jar和commons-io-2.4.jar两个组件,表单上传文件。
现象描述
上传文件的过程中,需要针对上传的文件在磁盘文件生成对应的temp文件,过程出现一些奇怪的问题,上传的文件一直在临时文件的存放磁盘找不到,纠结了一下午,实在是找不到自己写的代码的问题在哪里,debug之后发现文件是生成了,但是生成的文件的名称编码相对于内存中的编码小,导致针对zip文件进行解析的时候,总是提示找不到文件。
解决方法
- 1.下载commons-fileupload-1.3.1.jar源码包
https://github.com/apache/commons-fileupload
- 2.debug流程走起
备案
- 1.getStoreLocation() 返回空的文件
//存储在内存中文件,通过该方法获取的文件是空的
/**
* Returns the {@link java.io.File} object for the {@code FileItem}'s
* data's temporary location on the disk. Note that for
* {@code FileItem}s that have their data stored in memory,
* this method will return {@code null}. When handling large
* files, you can use {@link java.io.File#renameTo(java.io.File)} to
* move the file to new location without copying the data, if the
* source and destination locations reside within the same logical
* volume.
*
* @return The data file, or {@code null} if the data is stored in
* memory.
*/
public File getStoreLocation() {
if (dfos == null) {
return null;
}
if (isInMemory()) {
return null;
}
return dfos.getFile();
}
- 2.默认存储在文件中的,文件大小为10kb。
/**
* The threshold above which uploads will be stored on disk.
*/
private final int sizeThreshold;
/**
* The default threshold above which uploads will be stored on disk.
*/
public static final int DEFAULT_SIZE_THRESHOLD = 10240;
/**
* The threshold above which uploads will be stored on disk.
*/
private int sizeThreshold = DEFAULT_SIZE_THRESHOLD;
- 3.临时文件的路径获取
/**
* Creates and returns a {@link java.io.File File} representing a uniquely
* named temporary file in the configured repository path. The lifetime of
* the file is tied to the lifetime of the {@code FileItem} instance;
* the file will be deleted when the instance is garbage collected.
* <p>
* <b>Note: Subclasses that override this method must ensure that they return the
* same File each time.</b>
*
* @return The {@link java.io.File File} to be used for temporary storage.
*/
protected File getTempFile() {
if (tempFile == null) {
File tempDir = repository;
if (tempDir == null) {
tempDir = new File(System.getProperty("java.io.tmpdir"));
}
String tempFileName = format("upload_%s_%s.tmp", UID, getUniqueId());
tempFile = new File(tempDir, tempFileName);
}
return tempFile;
}
- 2.临时文件删除
/**
* Deletes the underlying storage for a file item, including deleting any
* associated temporary disk file. Although this storage will be deleted
* automatically when the {@code FileItem} instance is garbage
* collected, this method can be used to ensure that this is done at an
* earlier time, thus preserving system resources.
*/
@Override
public void delete() {
cachedContent = null;
File outputFile = getStoreLocation();
if (outputFile != null && !isInMemory() && outputFile.exists()) {
outputFile.delete();
}
}