SpringMVC实现文件上传

来源:互联网 发布:java包的作用是什么 编辑:程序博客网 时间:2024/05/08 17:52

为了上传文件,必须将HTML表格的entype属性值设置为multipart/form-data,像下面这样:

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>test</title></head><body>    <form action="upload.do" method="post" enctype="multipart/form-data">    <input type="file" name="file" /> <input type="submit" value="Submit" /></form>    <!-- 表格中必须包含类型为file的一个input元素,它会显示成一个按钮--></body></html>



后台的处理代码:

package scau.zxck.web.te.admin;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import java.io.File;/** * Created by 追追 on 2016/4/23. */@Controller@RequestMapping(value = "/test")public class test {    @RequestMapping(value = "/upload.do")    public String upload(@RequestParam(value = "file", required = false) MultipartFile file,                         HttpServletRequest request, ModelMap model) {        String path = request.getSession().getServletContext().getRealPath("url");//图片的保存地址        String fileName = file.getOriginalFilename();        System.out.println(path);        File targetFile = new File(path, fileName);        if(!targetFile.exists()){            targetFile.mkdirs();        }        try {            file.transferTo(targetFile);        } catch (Exception e) {            e.printStackTrace();        }        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);        System.out.println(request.getContextPath()+"/upload/"+fileName);        return "url";    }

MultipartFile接口:

上传到SpringMVC应用程序的文件会包含在一个MultipartFile对象中,我们唯一的任务就是用类型为MulipartFile的属性编写一个domain类,像上文代码一样,这里简单列出该接口(org.springframework.web.multipart.MultipartFile)的一些方法:

byte[ ]  getBytes()

它以字节数组的形式返回文件的内容

String getContenttype()

它返回文件的内容类型

InputStream getInputStream()

它返回一个InputStream,从中读取文件的内容

String getName()

它以多部分的形式返回参数的名称

String getOriginalFilename()

它返回客户端文件的本地名称

long getSize()

它以字节为单位,返回文件的大小

boolean isEmpty()

它表示上传文件是否为空

void transferTo(File destination)

它将上传的文件保存到目标目录下


0 0
原创粉丝点击