SSH框架文件上传

前台:

 <input type="file" name="upload">  

UploadUtils工具类:

public class UploadUtils {
    /**
     * 传入文件名称,返回唯一的名称
     * @param filename
     * @return
     */
    public static String getUUIDName(String filename){
        //先查找 从后往前找
        int index = filename.lastIndexOf(".");
        //截取后缀名
        String lastname = filename.substring(index,filename.length());
        //System.out.println(filename);
        //唯一字符串
        String uuid = UUID.randomUUID().toString().replace("-", "");//默认带有-
         
        return uuid+lastname;
    }
    public static void main(String[] args) {
        String filename = "gril.jsp";
        System.out.println(getUUIDName(filename));
    }
}

domain等文件中添加文件上传路径属性

WEB层代码(连同增加客户一起)

private File upload;
    private String uploadFileName;
    private String uploadContentType;
 
    public void setUpload(File upload) {
        this.upload = upload;
    }
 
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
 
    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
     
    public String save() throws IOException{
        //做文件的上传,说明用户选择了上传的文件
        if (uploadFileName!=null) {
            //打印
            //System.out.println("文件名称:"+uploadFileName);
            System.out.println("文件类型:"+uploadContentType);
            //把名称处理一下
            String uuidname = UploadUtils.getUUIDName(uploadFileName);
            //把文件上传到D:\\Tomcat8.0\\webapps\\upload
            String path = "D:\\Tomcat8.0\\webapps\\upload\\";
            //创建file对象
            File file = new File(path+uuidname);
            //简单方式
            FileUtils.copyFile(upload, file);//导org.apache.commons.io的包
             
            //把文件上传的路径,保存到客户表中
            customer.setFilepath(path+uuidname);
        }
        customerService.save(customer);
        return "save";
    }

在struts.xml文件中添加

<!-- 设置上传文件总大小 -->
    <constant name="struts.multipart.maxSize" value="20971520"></constant>
发布了50 篇原创文章 · 获赞 7 · 访问量 4416

猜你喜欢

转载自blog.csdn.net/qq_37822034/article/details/103864794
今日推荐