[SSM] Traditional way of uploading files

File upload jar package

Commons-fileuploadAnd commons-io
can be introduced with maven

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

View layer

First we will have a

 <input type="file" id="goodImgText" value="选择上传图片" name="url"/>
 
 <button type="button" class="btn " 
 id="save-btn">增加</button>
 

Here to select the uploaded file

Then we are jsin, use ajaxto upload files

$("#save-btn"").click(function () {
    
    
var files = $('#goodImgText').prop('files');
var formData = new FormData();
formData.append('goodImgText', files[0]);

$.ajax({
    
    
            url: "${APP_PATH}/fileupload",
            type: "POST",
            data: formData,
            dataType: 'JSON',
            cache: false,                  // 不缓存
            processData: false,            // jQuery不要去处理发送的数据
            contentType: false,
            async: false,
            success: function (result) {
    
    
                if (result.code == 100) {
    
    
                    alert("上传成功");
                } else {
    
    
                    alert("上传失败,此文件不是图片");
                }
            }
        })
}

Control layer

 @RequestMapping(value = "/fileupload", method = RequestMethod.POST)
    @ResponseBody
    public Msg fileUpload(HttpServletRequest servletRequest ) throws Exception {
    
    

        // 使用fileupload组件完成文件上传
        //上传的位置
        String path=servletRequest.getSession().getServletContext().getRealPath("/static/image/");
        //判断,该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
    
    
            //创建该文件夹
            System.out.println("不存在");
            //如果不存在,那么创建一个文件夹
            file.mkdirs();
        }

        //解析request对象,获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(servletRequest);
        //遍历
        for (FileItem item : items) {
    
    
            //进行判断,当前item对象是否是上传文件项
            if (item.isFormField()) {
    
    
                //说明普通表单项
            } else {
    
    
                String contentType = item.getContentType();
                //说明上传文件项
                //获取上传文件的名称
                String filename  = item.getName();
                //把文件的名称设置唯一值,uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid + "_" + filename;
                //完成文件上传
                item.write(new File(path, filename));
                //删除临时文件,如果文件大小大于10kb,那么删除,否则在磁盘上缓存
                item.delete();
                return Msg.success().add("fileName", filename);

            }
        }
        return Msg.fail();
    }

Configure the file size in the MVC configuration file

<!-- 配置文件上传解析器 --> 
<!-- id 的值是固定的-->
<bean id="multipartResolver" 
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 5MB --> <property name="maxUploadSize"> <value>5242880</value>
</property>
</bean>

Note :
The parser id for file upload is fixed, and no other name can be given, otherwise the binding of request parameters cannot be realized. (Not only files, other fields will not be bound)

Guess you like

Origin blog.csdn.net/Black_Customer/article/details/107614817