02.springmvc實現文件上傳

1.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<c:set var="basePath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> test file upload </title>   
</head>
<body>   
    <form  action="/InstaiElective/course/uploadCourseCover" method="post"   enctype="multipart/form-data" >
 
    parameter1: <input type="text"      name="parameter1"><br><br>
    parameter1: <input type="text"      name="parameter1"><br><br>
                <input type="file"      name="file"><br><br>
                <input type="submit"    name="submit" value="submit">
    </form>
</body>
</html>
2.controller文件:
        @RequestMapping(value = "/uploadCourseCover", method = RequestMethod.POST)
    public @ResponseBody ReturnData<String> uploadCourseCover(@RequestParam("file") MultipartFile file, HttpServletRequest request ) throws CustomException {
        ReturnData<String> rd = new ReturnData<String>();
                String parameter1 = request.getParameter("parameter1");
        String parameter2 = request.getParameter("parameter2");
        String picUrl = courseRepositoryService.upload(file,request);
        rd.setCode(Conss.RETURNDATA_SUCCEEDED);
        rd.setDesc("upload success");
        rd.setData(picUrl);
        return rd;
    }
3.service文件:
public String upload(MultipartFile file, HttpServletRequest request) {
        String absolutePath = null;
        if (!file.isEmpty()) {
            ServletContext sc = request.getSession().getServletContext();
                        // 設定文件保存的目錄
            String dir = sc.getRealPath("/img"); 
                        // 得到上傳時的文件名
            String fileName = file.getOriginalFilename();
            String strs[] = fileName.split("\\.");
            fileName = "";
            for(int i=0;i<strs.length-1;i++){
                fileName += strs[i];
            }
            //避免文件名重復 --重命名文件
            fileName = String.valueOf(System.currentTimeMillis()) + "." + strs[strs.length-1];
            try {
                FileUtils.writeByteArrayToFile(new File(dir, fileName), file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            absolutePath = "/img/" + fileName;
        }
        return absolutePath;
    }
4.文件下載:

http://www.cnblogs.com/ungshow/archive/2009/01/12/1374491.html
http://www.2cto.com/kf/201409/331289.html

5.讀取文件流在頁面輸出顯示--(防止看到文件路徑)

http://blog.csdn.net/woweipingzui/article/details/51037753

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容