SSM learning --springMVC road the next day _ to upload files to the server

First, add dependencies

Upload file required jar package, under maven project only needs to add a dependency

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

Second, write code

index.jsp:
Note here the file of the form name=“upload”, and the following file parser object name to be the same

<form action="upload/testUpload" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"><br>
    <input type="submit" value="上传">
</form>

uploadController:
second parameter MultipartFile formals upload, to form the corresponding file name attribute.
Must be the same

@Controller
@RequestMapping("upload")
public class uploadController {
	
    @RequestMapping("testUpload")
    public String testUpload(HttpServletRequest request, MultipartFile upload) throws IOException {
        System.out.println("testUpload方法执行了");
        //获取服务器路径,存入下面的upload子文件夹下
        String path = request.getSession().getServletContext().getRealPath("/upload");
        //根据目录新建这个文件夹
        File file = new File(path);
        //如果该文件夹不存在,创建该文件夹
        if (!file.exists()){
            file.mkdir();
        }
        //获取解析后该文件的文件名
        String fileName = upload.getOriginalFilename();
        //获取一个唯一指定的UUID,防止出现重复
        String uuid = UUID.randomUUID().toString().replace("-","").trim();
        fileName = uuid + "_" + fileName;
        //上传文件
        upload.transferTo(new File(path,fileName));
        //为了看看上传后的路径和文件名
        System.out.println(path);
        System.out.println(fileName);
        //执行成功则转向success.jsp页面
        return "success";
    }
}

Third, the configuration file parser object

id file parser object must if the multipartResolver.

<bean  id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--指定最大的上传大小,value以B为单位,如10M就是10*1024KB*1024B-->
        <property name="maxUploadSize" value="10485760"></property>
        <!--文件的默认编码-->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

The result:
upload two pictures called database properties, can be seen due to the unique uuid, covering the situation does not arise.
Here Insert Picture Description

Published 31 original articles · won praise 0 · Views 1215

Guess you like

Origin blog.csdn.net/SixthMagnitude/article/details/104317322