码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc文件上传示例

时间:2018-02-01 20:36:07      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:blank   last   Enctype   turn   and   tco   str   strong   spring   

 首先要导包,用的的包是:

commons-fileupload-*.*.*.jar

commons-io-*.*.jar

*号代表版本号

 这里给大家分享一下下载链接:https://files.cnblogs.com/files/chuanyueinlife/SpringMVC%E4%B8%8A%E4%BC%A0jar%E5%8C%85.zip

jsp页面:

<form action="upload.do" method="post" enctype="multipart/form-data">

        选择文件:<input type="file" name="file"> 
         <br>
         <input type="submit" value="提交"> </form>

Controller:

package controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
    @RequestMapping("upload.do")
    public String upload(HttpServletRequest request, String userName, @RequestParam(value = "file") MultipartFile file)
            throws IllegalStateException, IOException {
        String upload_path = request.getSession().getServletContext().getRealPath("upload");
        String file_name = file.getOriginalFilename();
        file_name = file_name.substring(file_name.lastIndexOf("\\") + 1);
        String final_pathname = upload_path + "\\" + UUID.randomUUID() + "-" + file_name;
        File f = new File(final_pathname);
        file.transferTo(f);

        return "forward:index.jsp";

    }
}

 Springmvc.xml文件配置:

<!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>10240000</value>
        </property>
    
    </bean>

 

springmvc文件上传示例

标签:blank   last   Enctype   turn   and   tco   str   strong   spring   

原文地址:https://www.cnblogs.com/chuanyueinlife/p/8400580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!