SpringBoot项目上传图片

前端部分:

1、上传图片窗口:

//=========================取消圖片============================
 var quxiao_image=function(image_name_temp,image_temp){
     Ext.getCmp(image_name_temp).setValue('');
     var image = Ext.get(image_temp).dom;
     image.src = Ext.BLANK_IMAGE_URL;
     image.src ='';
 }
 //============================上傳圖片==================
 var image_input=function(image_name_temp,image_temp){
 var uploadPanel =  new Ext.form.FormPanel({
             fileUpload: true,
             id:'fileUploadForm',
             frame:true,
             labelAlign:'right',
             buttonAlign:'center',
             labelWidth: 60,
             items: [{
                 xtype: 'textfield',
                 fieldLabel: 'File',
                 id: 'file',
                 inputType: 'file',
                 allowBlank:false,
                 listeners : {
                         "render":function(){
                               Ext.get('file').on("change",function(){
                         })
                   }
                 }
             }],
            buttons: [{
               text:'Upload',
               id:'tijiao',
               handler:function(){
                  var src=Ext.getCmp('file').getValue();
                  var filetype=src.split('.');
                  if((filetype[filetype.length-1].toLowerCase()!='jpg')
                	  && (filetype[filetype.length-1].toLowerCase()!='jpeg')
                	  && (filetype[filetype.length-1].toLowerCase()!='png')){
                     Ext.Msg.alert('Tip','Please select a picture in JPG or JPEG or PNG format!',function(){
                              uploadPanel.getForm().getEl().dom.reset();
                              Ext.getCmp('file').focus();
                        });
                     return;
                  }
                  if(src==''){
                     Ext.getCmp('file').focus();
                     return;
                  }

                  uploadPanel.getForm().submit({
                     method : 'post',
                     url:'uploadImages',
                     waitTitle: 'Just a moment, please',
                     waitMsg: 'Uploading ...',
                     success : function(form, action){
                              if(action.result.success){
                                           var path=Ext.getCmp('file').getValue();
                                            Ext.getCmp(image_name_temp).setValue(action.result.msg);
                                            var image = Ext.get(image_temp).dom;
                                            image.src = Ext.BLANK_IMAGE_URL;
                                            var fname=action.result.msg;
                                            image.src =fname;
                                            uploadPanel.getForm().getEl().dom.reset();
                                            win_image.close();

                              }else{
                                Ext.Msg.alert('Tip',action.result.msg);
                              }
                       },
                     failure: function(form, action){
                                Ext.Msg.alert('Tip',action.result.msg);
                       }
                   });
              }
            },{
               text: 'Close',
               handler:function(){
                      win_image.close();
             }
         }]

     });

 var win_image= new Ext.Window({
         title:'Pick Picture',
         width: 350,
         height:150,
         layout: 'fit',
         shadow:false,
         plain:true,
         modal:true,
         bodyStyle:'padding:5px;',
         closeAction:'close',
         items:uploadPanel
     }).show();
 win_image.on('hide',function(){
         uploadPanel.getForm().getEl().dom.reset();
 });
 }

2、图片集

圖片集/
 var tabs_form=new Ext.form.FormPanel({
       anchor:'100%',
       frame:true,
       //autoHeight:true,
       height:300,
       layout:'form',
       labelWidth:80,
       labelAlign:'right',
       buttonAlign:'center',
       items:[{
	           xtype:'hidden',
	           id:'image1_name_temp',
	           value:''
	        },{
               xtype:'hidden',
               id:'image2_name_temp',
               value:''
            },{
               xtype:'hidden',
               id:'image3_name_temp',
               value:''
            },{
              xtype:'hidden',
              id:'image4_name_temp',
              value:''
           },{
           layout:'column',
           items:[{
              columnWidth:.25,
              layout:'form',
              items:[{
                 xtype : 'box',
                 fieldLabel: 'Picture 1',
                 id : 'image_name1',
                 autoEl : {
                       anchor:'95%',
                       height : 200,
                       width: 200,
                       tag : 'img',
                       src :  Ext.BLANK_IMAGE_URL,
                       style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader

(sizingMethod=scale);',
                       complete : 'off',
                       id : 'image1'
                   }
                  },{
                     layout:'column',
                     items:[{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Upload Pic1',
                               handler:function(){
                                new image_input('image1_name_temp','image1');
                              }
                         }]
                       },{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Cancel Pic1',
                               handler:function(){
                               Ext.MessageBox.confirm('Tip!', 'Are you sure you want to delete?', function

(btn, text){
                                 if (btn == 'no') {
                                     return false;
                                 }
                                  new quxiao_image('image1_name_temp','image1');
                               });
                              }
                         }]
                       }]
                   }
             ]
           },{
              columnWidth:.25,
              layout:'form',
              items:[{
                 xtype : 'box',
                 fieldLabel: 'Picture 2',
                 id : 'image_name2',
                 autoEl : {
                       anchor:'95%',
                       height : 200,
                       width: 200,
                       tag : 'img',
                       src :  Ext.BLANK_IMAGE_URL,
                       style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader

(sizingMethod=scale);',
                       complete : 'off',
                       id : 'image2'
                   }
                  },{
                     layout:'column',
                     items:[{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Upload Pic2',
                               handler:function(){
                                new image_input('image2_name_temp','image2');
                              }
                         }]
                       },{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Cancel Pic2',
                               handler:function(){
                               Ext.MessageBox.confirm('Tip!', 'Are you sure you want to delete?', function

(btn, text){
                                 if (btn == 'no') {
                                     return false;
                                 }
                                  new quxiao_image('image2_name_temp','image2');
                               });
                              }
                         }]
                       }]
                   }
             ]
           },{
                    columnWidth:.25,
                    layout:'form',
                    items:[{
                       xtype : 'box',
                       fieldLabel: 'Picture 3',
                       id : 'image_name3',
                       autoEl : {
                             anchor:'95%',
                             height : 200,
                             width: 200,
                             tag : 'img',
                             src :  Ext.BLANK_IMAGE_URL,
                             style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader

(sizingMethod=scale);',
                             complete : 'off',
                             id : 'image3'
                         }
                     },{
                     layout:'column',
                     items:[{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Upload Pic3',
                               handler:function(){
                                new image_input('image3_name_temp','image3');
                              }
                         }]
                       },{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Cancel Pic3',
                               handler:function(){
                               Ext.MessageBox.confirm('Tip!', 'Are you sure you want to delete?', function

(btn, text){
                                 if (btn == 'no') {
                                     return false;
                                 }
                                  new quxiao_image('image3_name_temp','image3');
                               });
                              }
                         }]
                       }]
                   }
             ]
           },{
              columnWidth:.25,
              layout:'form',
              items:[{
                 xtype : 'box',
                 fieldLabel: 'Picture 4',
                 id : 'image_name4',
                 autoEl : {
                       anchor:'95%',
                       height : 200,
                       width: 200,
                       tag : 'img',
                       src :  Ext.BLANK_IMAGE_URL,
                       style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader

(sizingMethod=scale);',
                       complete : 'off',
                       id : 'image4'
                   }
                  },{
                     layout:'column',
                     items:[{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Upload Pic4',
                               handler:function(){
                                new image_input('image4_name_temp','image4');
                              }
                         }]
                       },{
                         columnWidth:.5,
                         layout:'form',
                         items:[{
                               xtype:'button',
                               text: 'Cancel Pic4',
                               handler:function(){
                               Ext.MessageBox.confirm('Tip!', 'Are you sure you want to delete?', function

(btn, text){
                                 if (btn == 'no') {
                                     return false;
                                 }
                                  new quxiao_image('image4_name_temp','image4');
                               });
                              }
                         }]
                       }]
                   }
             ]
           }
        ]
       }]
   });

 
 var tabs=new Ext.TabPanel({
     autoHeight:true
  });

  tabs.add({
     autoHeight:true,	 
     title:'Pictures',
     Layout:'fit',
     items:tabs_form
   });
  tabs.activate(0);

3、新增數據時,初始化圖片集

  Ext.get('image1').dom.src= Ext.BLANK_IMAGE_URL;
  Ext.get('image1').dom.src ='';
  Ext.getCmp('image1_name_temp').setValue('');
  Ext.get('image2').dom.src= Ext.BLANK_IMAGE_URL;
  Ext.get('image2').dom.src ='';
  Ext.getCmp('image2_name_temp').setValue('');
  Ext.get('image3').dom.src= Ext.BLANK_IMAGE_URL;
  Ext.get('image3').dom.src ='';
  Ext.getCmp('image3_name_temp').setValue('');
  Ext.get('image4').dom.src= Ext.BLANK_IMAGE_URL;
  Ext.get('image4').dom.src ='';
  Ext.getCmp('image4_name_temp').setValue('');

4、修改數據時,圖片集賦值

      Ext.getCmp('image1_name_temp').setValue(record[0].get('image_name1'));
      var image1 = Ext.get('image1').dom;
      image1.src = Ext.BLANK_IMAGE_URL;
      var fname=record[0].get('image_name1');
      image1.src =fname;
      
      Ext.getCmp('image2_name_temp').setValue(record[0].get('image_name2'));
      var image2 = Ext.get('image2').dom;
      image2.src = Ext.BLANK_IMAGE_URL;
      var fname=record[0].get('image_name2');
      image2.src =fname;
      
      Ext.getCmp('image3_name_temp').setValue(record[0].get('image_name3'));
      var image3 = Ext.get('image3').dom;
      image3.src = Ext.BLANK_IMAGE_URL;
      var fname=record[0].get('image_name3');
      image3.src =fname;
      
      Ext.getCmp('image4_name_temp').setValue(record[0].get('image_name4'));
      var image4 = Ext.get('image4').dom;
      image4.src = Ext.BLANK_IMAGE_URL;
      var fname=record[0].get('image_name4');
      image4.src =fname;    

application.yml 配置:

#圖片上傳絕對路徑
upload:
  filePath: C:/GVPV/imagesFromInput/uploadFile/

Java config,controller,server,xml部分:

1、新增配置類UploadFileConfig

package com.goodview.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "upload")
public class UploadFileConfig {

	private  String filePath;

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	@Override
	public String toString() {
		return "UploadFileConfig [filePath=" + filePath + "]";
	}
	
}

2、新增配置類WebMvcConfig,關聯圖片的絕對路徑和相對路徑 :

package com.goodview.config;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		//靜態跳轉頁
	    registry.addViewController("/").setViewName("forward:login.html");;
		//動態跳轉頁
	    //registry.addViewController("/").setViewName("login");
	}    
  
    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大KB,MB
        factory.setMaxFileSize(DataSize.parse("2MB"));
        //设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("10MB"));
        return factory.createMultipartConfig();
    }

    /** * 解决ie responsebody返回json的时候提示下载问题 * * @return */
    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        MediaType media = new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8"));
        supportedMediaTypes.add(media);
        jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
        return jsonConverter;
    }

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		// TODO Auto-generated method stub
		converters.add(customJackson2HttpMessageConverter());
	}
	
  
    @Resource
    UploadFileConfig uploadFileConfig;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/uploadFile/**").addResourceLocations("file:"+uploadFileConfig.getFilePath());


}

3、查詢數據

@PostMapping(value = "/getList")
	 @ResponseBody
	 public StoreResponseInfo<Nmat> getList(
			 @RequestParam(value = "nmat_id",required = true) String nmat_id,
			 @RequestParam(value = "start",required = true) int start,
			 @RequestParam(value = "limit",required = true) int limit,
			 HttpServletRequest request
			 ) throws UnsupportedEncodingException {  

		 StoreResponseInfo<Nmat> res = new StoreResponseInfo<Nmat>();
		 List<Nmat> list = new ArrayList<Nmat>();  	
		 int totalProperty=0;
	     String image_name1="";
	     String image_name2="";
	     String image_name3="";
	     String image_name4="";
	     String  filename1="";
	     String  filename2="";
	     String  filename3="";
	     String  filename4="";
	     String filePath1="";
	     String filePath2="";
	     String filePath3="";
	     String filePath4="";
	     byte[] get_image_name1=null;
	     byte[] get_image_name2=null;
	     byte[] get_image_name3=null;
	     byte[] get_image_name4=null;
		 try {   
			 totalProperty=Service.Count(nmat_id);
			 list=Service.getList(nmat_id, start, limit);
	    	 /*取出圖片,寫入指定文件夾*/
	    	 String realPath=fileConfig.getFilePath();
    		 for (int i=0; i<list.size();i++) {
        		image_name1=list.get(i).getImage_name1();        	            
	    		filename1=image_name1.substring(image_name1.lastIndexOf("/")+1,image_name1.length

()).replaceAll("'", " ").trim();
	    	    filePath1=realPath+filename1; 
	    	    File file1 =new File(filePath1);	    	   
	    	    if (!file1.exists()) {	    	    	
	    	    	get_image_name1 = list.get(i).getImage1();
	    			int len = get_image_name1.length;
	    			if(len!=-1) {
		    	    	FileOutputStream outputStream = new FileOutputStream(file1);
		    	    	outputStream.write(get_image_name1);// 将数组中的信息写入文件中
		    	    	outputStream.close();
	    	    	} 
	    	    }
        		image_name2=list.get(i).getImage_name2();        	            
	    		filename2=image_name1.substring(image_name2.lastIndexOf("/")+1,image_name2.length

()).replaceAll("'", " ").trim();
	    	    filePath2=realPath+filename2; 
	    	    File file2 =new File(filePath2);	    	   
	    	    if (!file2.exists()) {	    	    	
	    	    	get_image_name2 = list.get(i).getImage2();
	    			int len = get_image_name2.length;
	    			if(len!=-1) {
		    	    	FileOutputStream outputStream = new FileOutputStream(file2);
		    	    	outputStream.write(get_image_name2);// 将数组中的信息写入文件中
		    	    	outputStream.close();
	    	    	} 
	    	    }
        		image_name3=list.get(i).getImage_name3();        	            
	    		filename3=image_name3.substring(image_name3.lastIndexOf("/")+1,image_name3.length

()).replaceAll("'", " ").trim();
	    	    filePath3=realPath+filename3; 
	    	    File file3 =new File(filePath3);	    	   
	    	    if (!file3.exists()) {	    	    	
	    	    	get_image_name3 = list.get(i).getImage3();
	    			int len = get_image_name3.length;
	    			if(len!=-1) {
		    	    	FileOutputStream outputStream = new FileOutputStream(file3);
		    	    	outputStream.write(get_image_name3);// 将数组中的信息写入文件中
		    	    	outputStream.close();
	    	    	} 
	    	    }
        		image_name4=list.get(i).getImage_name4();        	            
	    		filename4=image_name4.substring(image_name4.lastIndexOf("/")+1,image_name4.length

()).replaceAll("'", " ").trim();
	    	    filePath4=realPath+filename4; 
	    	    File file4 =new File(filePath4);	    	   
	    	    if (!file4.exists()) {	    	    	
	    	    	get_image_name4 = list.get(i).getImage4();
	    			int len = get_image_name4.length;
	    			if(len!=-1) {
		    	    	FileOutputStream outputStream = new FileOutputStream(file4);
		    	    	outputStream.write(get_image_name4);// 将数组中的信息写入文件中
		    	    	outputStream.close();
	    	    	} 
	    	    }
    		}
		 } catch (Exception e) {			
			 e.printStackTrace();	
			 return res;
		 }  
		 res.totalProperty=totalProperty;
		 res.root = list;
		 //System.out.println(res);
		 return res;
	 } 

4、更新新增,關於圖片的部份:

public int update(String nmat_json) throws Exception {
        byte[] btye_images1 = null;
    	byte[] btye_images2 = null;
    	byte[] btye_images3 = null;
    	byte[] btye_images4 = null;
    	String image_name1="";
    	String image_name2="";
    	String image_name3="";
    	String image_name4="";
    	 //获取绝对路径
        String realPath=fileConfig.getFilePath();
		for (Nmat nmat : list) {
	    	image_name1=nmat.getImage_name1();		   
			String filename1=image_name1.substring(image_name1.lastIndexOf

("/")+1,image_name1.length()).replaceAll("'", " ").trim();
		    String filePath1=realPath+filename1;    		
			FileInputStream fis1=null;
			File file1 = new File(filePath1); 
			if (!"".equals(filename1)) {
		    		fis1 = new FileInputStream(file1);
		    		btye_images1=toByteArray(fis1);
		    		nmat.setImage1(btye_images1);	
			}
			image_name2=nmat.getImage_name2();	
			String filename2=image_name2.substring(image_name2.lastIndexOf

("/")+1,image_name2.length()).replaceAll("'", " ").trim();
		    String filePath2=realPath+filename2;    		
			FileInputStream fis2=null;
			File file2 = new File(filePath2); 
			if (!"".equals(filename2)) {
		    		fis2 = new FileInputStream(file2);
		    		btye_images2=toByteArray(fis2);
		    		nmat.setImage2(btye_images2);
			}
			image_name3=nmat.getImage_name3();	
			String filename3=image_name3.substring(image_name3.lastIndexOf

("/")+1,image_name3.length()).replaceAll("'", " ").trim();
		    String filePath3=realPath+filename3;    		
			FileInputStream fis3=null;
			File file3 = new File(filePath3); 
			if (!"".equals(filename3)) {
		    		fis3 = new FileInputStream(file3);
		    		btye_images3=toByteArray(fis3);
		    		nmat.setImage3(btye_images3);
			}
			image_name4=nmat.getImage_name4();
			String filename4=image_name4.substring(image_name4.lastIndexOf

("/")+1,image_name4.length()).replaceAll("'", " ").trim();
		    String filePath4=realPath+filename4;    		
			FileInputStream fis4=null;
			File file4 = new File(filePath4); 
			if (!"".equals(filename4)) {
		    		fis1 = new FileInputStream(file4);
		    		btye_images4=toByteArray(fis4);
		    		nmat.setImage4(btye_images4); 	
			}		
		}
		
}

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

5、更新圖片的xml部份

			image1 = #{image1,jdbcType=BINARY},
			image_name1 = #{image_name1,jdbcType=VARCHAR},
			image2 = #{image2,jdbcType=BINARY},
			image_name2 = #{image_name2,jdbcType=VARCHAR},
			image3 = #{image3,jdbcType=BINARY},
			image_name3 = #{image_name3,jdbcType=VARCHAR},
			image4 = #{image4,jdbcType=BINARY},
			image_name4 =#{image_name4,jdbcType=VARCHAR}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值