/**
* 上传文件
*
* @param tempfile文件对象
* @param srcurl原始存放地址
* @param uploadFileFileName文件名称
* @param uploadFileContentType文件类型
* @param dir指定文件夹 例如 upload
*
* @return
*/
public String fileupload(File tempfile, String srcurl,
String uploadFileFileName, String uploadFileContentType, String dir) throws IOException
{
if (tempfile == null)
return null;
if (uploadFileFileName == null)
return null;
if (null == dir || dir.length() == 0)
dir = “upload”;
// 基于myFile创建一个文件输入流
InputStream is = new FileInputStream(tempfile);
// 设置上传文件目录
String datetime = System.currentTimeMillis() + “”;
String uploadPath = “”;
if (StringUtils.isNotBlank(srcurl))
{
try
{
//uploadPath = ServletActionContext.getServletContext().getRealPath(“/” + dir + “/”) + “/” + srcurl.substring(0, srcurl.lastIndexOf(“/”));
//原文件路径
uploadPath = ServletActionContext.getServletContext().getRealPath(“/” + srcurl.substring(0, srcurl.lastIndexOf(“/”)));
} catch (Exception e)
{
uploadPath = ServletActionContext.getServletContext().getRealPath(“/” + dir + “/” + datetime + “/”);
}
System.out.println(uploadPath);
} else
{
//如果原文件路径不存在,则重新生成新路径
uploadPath = ServletActionContext.getServletContext().getRealPath(“/” + dir + “/” + datetime + “/”);
}
uploadFileFileName = getFileName(uploadFileFileName, uploadPath);
File file = new File(uploadPath);
if (!file.exists())
file.mkdirs();
// 设置目标文件
File toFile = new File(uploadPath, uploadFileFileName);
// 创建一个输出流
OutputStream os = new FileOutputStream(toFile);
// 设置缓存
byte[] buffer = new byte[1024];
int length = 0;
// 读取myFile文件输出到toFile文件中
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
// 关闭输入流
is.close();
// 关闭输出流
os.close();
uploadPath = uploadPath.replaceAll("\\\\", "/");
String filepath = (uploadPath + "/" + uploadFileFileName).substring((uploadPath + "/" + uploadFileFileName).indexOf(dir));
return (filepath.replaceAll("\\\\", "/"));
}
public String getFileName(String uploadFileFileName, String uploadPath)
{
try
{
if (null != uploadFileFileName)
{
uploadFileFileName = UUID.randomUUID().toString() + uploadFileFileName.substring(uploadFileFileName.lastIndexOf("."));
}
File file = new File(uploadPath + uploadFileFileName);
if (file.exists())
{
uploadFileFileName = getFileName(uploadFileFileName, uploadPath);
}
return uploadFileFileName;
} catch (Exception e)
{
e.printStackTrace();
}
return uploadFileFileName;
}