spring MVC 文件上传简单示例

这里使用的是form 表单上传,所以需要设置form的enctype=”multipart/form-data”。

uplaodFile.jsp

<form id="questionForm" action="<%=request.getContextPath()%>/insertAnswerInfo.action"
method="post" enctype="multipart/form-data" >
<textarea id="hqcontent" name="answerContent"></textarea>
<input type="file" name="file" class="upload"  onchange="Javascript:validate_img(this);">
<input id="subBtn" class="btn" type="submit" title="提交"  value="提交"/>
</form>

图片上传到服务器,数据库里存储的是文件的上传路径,用字段filePath存储。

uploadController.java

@Controller
public class uploadController{

    @Autowired
    private HdCommunicationService hdCommunicationService;

    @RequestMapping(value = "/insertAnswerInfo")
        public ModelAndView insertPersonalAnswer(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request, HttpServletResponse response,
            ModelAndView model) {

            //String realPath = request.getSession().getServletContext().getRealPath("/upload");

            String url = " ";
            try {
             url = UploadFileUtil.multipartUploadUtil(file,  request);
            } catch (IOException e) {

                e.printStackTrace();
            } catch (Exception e) {

                e.printStackTrace();
            }
            String content = request.getParameter("answerContent");

            HdCommunication communication = new HdCommunication();
                communication.setContent(content);
                communication.setFilePath(url);
            hdCommunicationService.insertPersonQuestion(communication);

            model.setViewName("redirect:/userMain.action?userName="+idcard+"&password="+password);

            return model;

        }

}

工具类:UploadFileUtil.java


public class UploadFileUtil {

    /**
     * 
     * <b>功能:上传</b><br>
     * <br>
     * @Author:predestinate
     * @param file:要上传的文件
     * @param request
     * @return 返回上传的路径+文件名,可直接保存到数据库
     * @throws Exception
     * @throws IOException String
     *
     */

    public static String  multipartUploadUtil(MultipartFile file,HttpServletRequest request) throws Exception, IOException {

        String result = "";
        //如果参数为空则返回空
        if(file == null ){
            return result;
        }

        //获取文件名称
        String filename = file.getOriginalFilename();

        //获取文件扩展名
        String extension = FilenameUtils.getExtension(filename);

        if(filename!=null && !filename.equals("") && extension!=null && !extension.equals("")){

        //图片名称生成策略:采用时间格式(精确到秒)并追加随机5位(10以内)数字
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileDate = df.format(new Date());

        //年月日时分秒_五位随机数.扩展名
        String picName = "/upload/"+fileDate+"_"+UploadFileUtil.getFixLenthString(5)+"."+extension;
        //获取文件上传路径
        Properties prop = new Properties();
        InputStream in = UploadFileUtil.class.getResourceAsStream("/resources/uploadFileURL.properties");
        prop.load(in);
        String absoluteURL = prop.getProperty("absoluteURL");

        File targetFile = new File(absoluteURL,picName);

        // 创建父级目录
        File p  = targetFile.getParentFile();
        if(!p.exists()){
            p.mkdirs();
        }
        //如果路径不存在,就创建
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        file.transferTo(targetFile);

        String basePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort();

        return basePath+absoluteURL+picName;
        }

        return result;
    }

    /*
     * 返回长度为【strLength】的随机数,在前面补0
     */
    private static String getFixLenthString(int strLength) {

        Random rm = new Random();

        // 获得随机数
        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);

        // 将获得的获得随机数转化为字符串
        String fixLenthString = String.valueOf(pross);

        // 返回固定的长度的随机数
        return fixLenthString.substring(1, strLength + 1);
    }

}

properties配置文件:resources目录下的uploadFileURL.properties

absoluteURL=/文件名
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值