`

spring mvc 上传文件

阅读更多
applicationContext.xml
<!-- 用于文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">


Controller

@RequestMapping(params = "method=upload")
    public String upload(FileUploadBean bean, BindingResult result,HttpServletRequest request,ModelMap modelMap) throws Exception{
        CommonsMultipartFile file = bean.getFile();
        File file1 = UploadUtil.saveFileFromInputStream(file, request.getRealPath("/") + "upload/customer/", file.getOriginalFilename());
        try {
            if(file1 != null)
                UploadUtil.importCustomer(file1,customerService);
        } catch (Exception e) {
            e.printStackTrace();

        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success","ok");
        modelMap.put("jsonstring", jsonObject.toString());
        return "json";
    }


保存文件的方法
/** 保存文件
     * @param commonsMultipartFile
     * @param path
     * @param filename
     * @throws IOException
     */
    public static File saveFileFromInputStream(CommonsMultipartFile commonsMultipartFile,String path,String filename) throws IOException {
        InputStream stream = commonsMultipartFile.getInputStream();
        if(stream.read() == -1)return null;
        String timeString = DateUtil.getLongCompactDate(new Timestamp(System.currentTimeMillis()));
        File filePath = new File(path);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        String fileName = path+"/"+timeString+"."+filename.substring(filename.lastIndexOf(".")+1,filename.length());
        File file = new File(fileName);
        try {
            commonsMultipartFile.getFileItem().write(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics