图片上传

jsp 页面:

<form action="file/uploading" method="post" enctype="multipart/form-data" >
        <input type="file" name = "fileName" ><p>
        <input type = "submit" value = "提交" >
</form>

 

java Controller 层

**
 * 图片上传接口
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {
    @RequestMapping(value = "/uploading", method = RequestMethod.POST)
    public String uploading(@RequestParam("fileName") CommonsMultipartFile file, HttpServletRequest request, ModelMap model)
            throws IOException {
        String pathName = file.getOriginalFilename(); // 获取原文件名
        String newPathName = UUID.randomUUID() + pathName; // 新名字、防止冲突

        // 获取项目路径
        ServletContext servletContext = request.getSession().getServletContext();

        // 设置上传位置
        String path = servletContext.getRealPath("/upload") + "/";

        // 判断此文件夹是否存在, 否则创建文件夹
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }

        // 判断文件是否等于空
        if (!file.isEmpty()) {
            FileOutputStream fos = new FileOutputStream(path + newPathName);
            InputStream inputStream = file.getInputStream();

            int i = 0;
            while ((i = inputStream.read()) != -1) {
                fos.write(i);
            }
            fos.close();
            inputStream.close();
        }
        String pathURL = "/upload/"+newPathName;
        // 保存文件地址,用于JSP页面回显
        request.setAttribute("pathURL", pathURL);
        
        return pathURL;
    }
}


获取图片 jsp 页面:

<img alt="上传图片" src="${pageContext.request.contextPath }<%=url %>">

posted @ 2016-09-19 10:44  26个字符的地狱  阅读(342)  评论(0)    收藏  举报