后端接收前端传过来的图片并保存到本地

依赖

	<dependency>
    	<groupId>commons-fileuploadgroupId>
    	<artifactId>commons-fileuploadartifactId>
    	<version>1.2.1version>
    dependency>
    
    <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.5version>
	dependency>

Service

	private String filePath="D:/xxx/xxx"; //定义上传文件的存放位置
	
	public String upLoadFile(MultipartFile upload){
		
		          
        //判断文件夹是否存在,不存在则创建
        File file=new File(filePath); 
       
        if(!file.exists()){
        	file.mkdirs();
        }
        String originalFileName = upload.getOriginalFilename();//获取原始图片的扩展名
		String newFileName = UUID.randomUUID()+originalFileName;  
        String newFilePath=filePath+newFileName; //新文件的路径
         
        try {
        	upload.transferTo(new File(newFilePath));  //将传来的文件写入新建的文件
        	return newFileName;
        }catch (IllegalStateException e ) {
        	//处理异常
        }catch(IOException e1){
        	//处理异常
        }	
	}

xml配置

	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="10485760">property>
		<property name="defaultEncoding" value="utf-8">property>
	bean>

你可能感兴趣的:(java)