上传文件

/**
* 上传文件
*
* @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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值