zoukankan      html  css  js  c++  java
  • spring mvc 上传文件配置及格式

    文件上传#

    1.配置

    在spring mvc的配置文件中配置文件上传的Bean

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

    增加文件上传的jar包。commons-fileupload-1.2.2.jar、commons-io-2.4.jar

    2.结构

    1.前台页面

    表单增加 enctype="multipart/form-data"

    表单增加文件上传标签 <input type="file" name="items_pic"/>

    <form id="itemForm" action="" method="post" enctype="multipart/form-data">
    	<input type="file"  name="items_pic"/> 
    </form>
    

    2.后台代码

    Controller方法参加图片参数MultipartFile items_pic//接收商品图片

    注意:参数名要与前台的参数名一致。

    @RequestMapping("/editItemsSubmit")
    public String editItemsSubmit(MultipartFile items_pic) throws Exception {		
    	//原始名称
    	String originalFilename = items_pic.getOriginalFilename();
    	//上传图片
    	if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){
    		
    		//存储图片的物理路径
    		String pic_path = "F:\develop\upload\temp\";
    		//新的图片名称
    		String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
    		//新图片
    		File newFile = new File(pic_path+newFileName);
    		//将内存中的数据写入磁盘
    		items_pic.transferTo(newFile);
    		//将新图片名称写到itemsCustom中
    		itemsCustom.setPic(newFileName);
    	}	
    	return "success";
    }
    

    3.注意:使用的时候发现一个问题,上传中文文件接收不到文件名,数字和英文的可以。

    这时候需要把tomcat的8080端口(HTTP连接器的端口标签,protocol="HTTP/1.1"的那个)和8080端口跳转的端口(8443,如果没有这个端口不加也行)的标签末尾加上URIEncoding="UTF-8",亲测可用。

    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8" />
  • 相关阅读:
    二维数组
    找一个数组的最大和的连续子数组(时间复杂度 O(n))(二)
    第一阶段SCRUM冲刺 01
    统计单词
    软件工程--第九周学习进度
    《人件》阅读笔记03
    用户模板和用户场景分析
    软件工程--第八周学习进度
    一维数组代码实现可视化
    《人件》阅读笔记02
  • 原文地址:https://www.cnblogs.com/zhuani21/p/5287976.html
Copyright © 2011-2022 走看看