文件上传:图片实例

实例:http://www.runoob.com/jsp/jsp-file-uploading.html

1.jsp

前端发送文件到后台,可以使用Form表单提交或者设置<input file onchang="checkImg(this.value)"/>,前者可以使用<button submit>,也可以使用<button οnclick="fun();">,fun()中使用$.AjaxSubmit({...});。

<form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
    选择一个文件:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="上传" />
</form>method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
    选择一个文件:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="上传" />
</form>

 

2.后台

 后台接收文件,使用InputStream和OutputStream将文件存储到相应位置。

1.接收

使用参数接收文件@RequestParam(value=“file”,required=“false”)MultipartFile file

2.设置路径和文件名

3.保存文件

项目路径获取,保存路径设置;判断路径是否存在,不存在则创建;

文件名获取,保存文件名设置;

InputStream和OutputStream建立,将文件输出保存到指定位置。

// 获得原始文件名  
        String fileName = file.getOriginalFilename();  
        System.out.println("原始文件名:" + fileName);  
        // 新文件名  
        String newFileName = UUID.randomUUID() + fileName;  //可自定
  
        // 获得项目的路径  
        ServletContext sc = request.getSession().getServletContext();  
        // 上传位置  
        String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录  
  
        File f = new File(path);  
        if (!f.exists())  
            f.mkdirs();  
        if (!file.isEmpty()) {  
            try {  
                FileOutputStream fos = new FileOutputStream(path + newFileName);  
                InputStream in = file.getInputStream();  
                int b = 0;  
                while ((b = in.read()) != -1) {  
                    fos.write(b);  
                }  
                fos.close();  
                in.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
        System.out.println("上传图片到:" + path + newFileName);  
        // 保存文件地址,用于JSP页面回显  
        model.addAttribute("fileUrl", path + newFileName);  file.getOriginalFilename();  
        System.out.println("原始文件名:" + fileName);  
        // 新文件名  
        String newFileName = UUID.randomUUID() + fileName;  //可自定
  
        // 获得项目的路径  
        ServletContext sc = request.getSession().getServletContext();  
        // 上传位置  
        String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录  
  
        File f = new File(path);  
        if (!f.exists())  
            f.mkdirs();  
        if (!file.isEmpty()) {  
            try {  
                FileOutputStream fos = new FileOutputStream(path + newFileName);  
                InputStream in = file.getInputStream();  
                int b = 0;  
                while ((b = in.read()) != -1) {  
                    fos.write(b);  
                }  
                fos.close();  
                in.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
        System.out.println("上传图片到:" + path + newFileName);  
        // 保存文件地址,用于JSP页面回显  
        model.addAttribute("fileUrl", path + newFileName); 

 

3.待测

http://blog.csdn.net/qian_ch/article/details/69258465 :文件流上传,对象上传,文件下载
http://blog.csdn.net/evankaka/article/details/45826697/ :文件上传,下载
https://www.cnblogs.com/fjsnail/p/3491033.html :三种文件上传方式:Stream、Transto、Spring提供方法
1.
@RequestMapping("/onefile2")  
public String oneFileUpload2(HttpServletRequest request,  
        HttpServletResponse response) throws Exception {  
    CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());  
    if (cmr.isMultipart(request)) {  
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);  
        Iterator<String> files = mRequest.getFileNames();  
        while (files.hasNext()) {  
            MultipartFile mFile = mRequest.getFile(files.next());  
            if (mFile != null) {  
                String fileName = UUID.randomUUID()  
                        + mFile.getOriginalFilename();  
                String path = "d:/upload/" + fileName;  
  
                File localFile = new File(path);  
                mFile.transferTo(localFile);  
                request.setAttribute("fileUrl", path);  
            }  
        }  
    }  
    return "fileUpload";  
}  CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());  
    if (cmr.isMultipart(request)) {  
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);  
        Iterator<String> files = mRequest.getFileNames();  
        while (files.hasNext()) {  
            MultipartFile mFile = mRequest.getFile(files.next());  
            if (mFile != null) {  
                String fileName = UUID.randomUUID()  
                        + mFile.getOriginalFilename();  
                String path = "d:/upload/" + fileName;  
  
                File localFile = new File(path);  
                mFile.transferTo(localFile);  
                request.setAttribute("fileUrl", path);  
            }  
        }  
    }  
    return "fileUpload";  
} 

2.

//上传文件会自动绑定到MultipartFile中
     @RequestMapping(value="/upload",method=RequestMethod.POST)
     public String upload(HttpServletRequest request,
            @RequestParam("description") String description,
            @RequestParam("file") MultipartFile file) throws Exception {

        System.out.println(description);
        //如果文件不为空,写入上传路径
        if(!file.isEmpty()) {
            //上传文件路径
            String path = request.getServletContext().getRealPath("/images/");
            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            //判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) { 
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));
            return "success";
        } else {
            return "error";
        }

     }file.transferTo(new File(path + File.separator + filename));
            return "success";
        } else {
            return "error";
        }

     }

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值