一、在properties文件中添加图片要上传和回显的路径
上传的路径:
#本地环境路径

image.uploadLocation=uploaded/image
#Linux环境路径
#image.uploadLocation=/usr/local/img

回显的路径:
#本地环境路径

image.virtualLocation=file:///F:/works/STSWorkSpace/localpreferences_manager/src/main/webapp/uploaded/image/
#Linux环境路径
#image.virtualLocation=file:///usr/local/img/

图片丢失加载默认图片的路径:

image.defaultLocation=classpath:/static/assets/imgs/

二、图片上传
1、html中代码如下:

<div class="form-group">
				<label>上传图片:</label>
				 <input id="input-id" type="file" class="file" name="files" data-preview-file-type="text">
</div>

2、js代码如下(我是表单和图片异步上传的,图片不在form表单里)

$addUserModal.find("#doAddUser").click(function () {
	var data = $('#addUserForm').serialize();
	uploadFile(data);
});  

接下来是表单提交并且判断是否有图片上传,如果有上传则调用上传图片的方法。


function uploadFile(data) {
	 
		$.ajax({
			url: basePath + "sys/fromPost",  //提交表单的路径
			type: 'post',
			cache: false,
			data: data,
			dataType: "json",
			success: function(result) {
				productId = result.productId;
				shopId = result.shopId;
				type = result.type;
				 //不上传文件时,不触发bootstrap 上传插件的初始化方法。仅将表单里面的(除文件以外的)内容提交,
				$('#input-id').fileinput('upload'); 
              if ($("#input-id").val() != "") {
              	//fileInput(); //触发插件开始上传。
              	$('#input-id').fileinput('upload'); //触发插件开始上传。
              	//uploadImg(shopId, productId);
              }
              else {
              	
                  $("#bootstraptable_fishcontent").bootstrapTable("refresh");
              }
		},
		error:function(){
			
		}
	});
} 

图片上传的方法

function fileInput() {
	//alert("1111");
    $("#input-id").fileinput({
    	language: 'zh', 		//设置语言
        theme: 'explorer-fa',
        uploadUrl:basePath + 'sys/fromPhotoPost',  //上传图片的路径,
        enctype: 'multipart/form-data',
        minFileCount: 1,                                        // 最小上传数量
        maxFileCount: 1, 										// 最大上传数量
        overwriteInitial: false,                        		// 覆盖初始预览内容和标题设置
        allowedFileExtensions : ["jpg","png","gif","bmp","jpeg","JPG","PNG","GIF","BMP","JPEG"],
        showCancel:false,                                       // 显示取消按钮
        showZoom:false,                                         // 显示预览按钮
        showCaption:true,                                  	    // 显示文件文本框11111
        dropZoneEnabled:false,                          		// 是否可拖拽1111
        showUpload: false,
        maxFileSize: 4000,
        uploadLabel:"上传",                         			// 上传按钮内容
        browseLabel: '选择',                            		// 浏览按钮内容
        showRemove:true,                                       // 显示移除按钮
        previewFileIconSettings: {
            'docx': '<i class="fa fa-file-word-o text-primary"></i>',
            'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
            'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
            'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
            'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
            'sql': '<i class="fa fa-file-word-o text-primary"></i>',
        },     
        hideThumbnailContent:false,                  // 是否隐藏文件内容
        fileActionSettings: {                               // 在预览窗口中为新选择的文件缩略图设置文件操作的对象配置
            showRemove: false,                                   // 显示删除按钮
            showUpload: false,                                   // 显示上传按钮
            showDownload: false,                            // 显示下载按钮
            showZoom: false,                                    // 显示预览按钮1111
            showDrag: false,                                        // 显示拖拽111
           // removeIcon: '<i class="fa fa-trash"></i>',   // 删除图标 
           // uploadIcon: '<i class="fa fa-upload"></i>',     // 上传图标
            //uploadRetryIcon: '<i class="fa fa-repeat"></i>'  // 重试图标
        },
        initialPreviewAsData: true,
        initialPreview: [
           
        ],
        uploadExtraData:function (previewId, index) {
            var obj = {};
            obj.productId = productId;
            obj.shopId = shopId;
            obj.type = type;
            return obj;
        }
    }).on("fileuploaded", function (event, data, previewId, index) {
    	 var form = data.form, files = data.files, extra = data.extra,
         response = data.response, reader = data.reader; 
    	 /*$.modal.close("#addUserForm");
         $("#bootstraptable_fishcontent").bootstrapTable("refresh");*/
         $('#userTable').bootstrapTable("refresh");
    }).on('filepreupload', function(event, data, previewId, index) {  //批量成功后的回调函数
    	 var form = data.form, files = data.files, extra = data.extra,
         response = data.response, reader = data.reader;
    	//$.modal.close("#addUserForm");
        $("#bootstraptable_fishcontent").bootstrapTable("refresh");
    	//$("#addUserModal")..modal("hide");
    	$('#userTable').bootstrapTable("refresh");
    });
  };

Controller接收图片上传的关键代码如下
首先拿到配置文件中的路径

@Value("${image.uploadLocation}")
	private String uploadLocation;

然后编写业务逻辑及实现图片上传,业务逻辑代码没借鉴价值,我就删掉了。注意:一定要给前端返回一个json,不然可能页面显示会有问题。

@PostMapping("sys/fromPhotoPost")
    @ResponseBody
    public Map<String,String> product2(HttpServletRequest request,@RequestParam MultipartFile[] files,@RequestParam String productId,@RequestParam String shopId,@RequestParam String type) throws Exception{
		
		for (MultipartFile file : files) {
            //根据时间戳创建新的图片名,这样即便是第二次上传相同名称的图片,也不会把第一次的图片覆盖了			
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //linux下路径请修改配置文件,然后直接使用uploadLocation + File.separator + fileName
            String destFileName =request.getSession().getServletContext().getRealPath("") +  uploadLocation + File.separator + fileName;
            String uploadUrl = uploadLocation + File.separator + fileName;
            System.out.println(destFileName);
            //第一次运行的时候,这个图片所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
            try {
				File destFile = new File(destFileName);
				if(!destFile.getParentFile().isDirectory()) {
					destFile.getParentFile().mkdirs();
				}      
				//把浏览器上传的图片复制到希望的位置
				file.transferTo(destFile);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		Map<String, String> map = new HashMap<String,String>();
        map.put("productId", productId);
        map.put("shopId", shopId);
        return map;
    }

三、图片修改(修改时会展示原来的图片)
前端html代码:

<div class="form-group">
				<label>替换原图片:</label>
				 <input id="input-id" type="file" name="files">
</div>

js中关键代码:
1、首先根据图片id查询出来图片的信息

function firstPicture(){
	var did = $("#did").val();//获取要修改的图片的id
	var id = did*1;
	$.ajax({
        type : "post",
        url : basePath + "sys/findPhotoById",
        data:{
        	"id" : id
        },
        dataType : "json",
        success : function(data) {
         showFiles(data); 
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
               alert('操作失败!');
                    }
    })
}

2、图片修改,这里的basePath 是thymeleaf写法,在html中定义的var basePath = /[[@{/}]]/;
代码中的image是在后端中配置图片回显的虚拟路径,在下文后端中会说明,后端配好后前端可以直接用。

function showFiles(data){
 	// 预览文件json数据组
     var preList;
     var url = data.uploadLocation;
     url = url.replace("\\\\", "\/\/");
     url = url.replace("\\", "\/");
     url = url.replace("\\", "\/");
     var fileNames = data.imageName;;
 		// 数据库存的路径
 		if(data.imageName.indexOf("png")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("jpg")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("JPG")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("PNG")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("gif")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("GIF")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("bmp")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("BMP")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("jpeg")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("JPEG")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("gif")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		} else if(data.imageName.indexOf("GIF")>0){
 			preList = "<img src=\""+basePath+"image/"+fileNames+"\" class=\"file-preview-image\" style='width:198px;height:198px;'>";
 		}
 		
 	   var previewJson = preList;
     // 与上面 预览文件的json数据组 对应的config数据
     var preConfigList;
 		var tjson = {caption: data.imageName, // 展示的文件名
 					width: '10px', 
 					url:basePath + 'sys/delectPhotoById', // 删除url
 					key: data.id, // 删除是Ajax向后台传递的参数
 					extra: {id: 100}
 					};
 		preConfigList = tjson;    
  // 上传组件初始化
 		//alert("111");
	 $('#input-id').fileinput({
		 language: 'zh', 		//设置语言
		 theme: 'explorer-fas',
         uploadUrl: basePath + 'sys/updatePhotoPost',
         enctype: 'multipart/form-data',
         minFileCount: 1,                                        // 最小上传数量
         maxFileCount: 1, 										// 最大上传数量
         overwriteInitial: false,
         allowedFileExtensions : ["jpg","png","gif","bmp","jpeg","JPEG","JPG","PNG","GIF","BMP"],
         showCancel:false,                                       // 显示取消按钮
         showZoom:false,                                         // 显示预览按钮
         showCaption:true,                                  	    // 显示文件文本框
         dropZoneEnabled:false,                          		// 是否可拖拽
         showUpload: false,   // 布尔值,是否显示文件上传按钮。默认值为true。它默认为一个表单提交按钮,除非指定了uploadUrl属性。                                   		// 浏览按钮内容
         showRemove:true,                                       // 显示移除按钮
         uploadAsync:true,  //多个文件的批上传是否异步/并行。默认为true。         
         showPreview:true, //布尔值,是否显示文件预览。默认值为true。 
         maxFileSize:4000,
         initialPreviewShowDelete:true,//布尔值,是否为每个使用initialPreview创建的缩略图显示删除按钮。
         msgFilesTooMany: "选择上传的文件数量 超过允许的最大数值!",//当文件计数超过Max FrimeCuNT中设置的最大计数时要显示的消息
         initialPreview: previewJson,
         previewSettings: {            image: {width: "100px", height: "100px"},        }, 
         previewFileIcon: '<i class="fa fa-file"></i>',
          fileActionSettings: {                               // 在预览窗口中为新选择的文件缩略图设置文件操作的对象配置
             showRemove: false,                                   // 显示删除按钮
             showDownload: false,                            // 显示下载按钮
             showZoom: false,                                    // 显示预览按钮
             showDrag: false,                                        // 显示拖拽
             showUpload: false,                                   // 显示上传按钮
             //removeIcon: '<i class="fa fa-trash"></i>',   // 删除图标 
             //uploadIcon: '<i class="fa fa-upload"></i>',     // 上传图标
             //uploadRetryIcon: '<i class="fa fa-repeat"></i>'  // 重试图标
         },
         allowedPreviewTypes: ['image'],
         previewFileIconSettings: {
             'docx': '<i class="fa fa-file-word-o text-primary"></i>',
             'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
             'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
             'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
             'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
             'sql': '<i class="fa fa-file-word-o text-primary"></i>',
         },
         //initialPreviewConfig: preConfigList,
         initialPreviewConfig: [
             {caption: "", // 展示的文件名
 					width: '300px', 
 					url:'/sys/delectPhotoById', // 删除url
 					key: data.id}
         ],
         uploadExtraData:function (previewId, index) {
             //向后台传递id作为额外参数,是后台可以根据id修改对应的图片地址。
        	 var obj = {};
             obj.productId = productId;
             obj.shopId = shopId;
             obj.ids = ids;
             obj.type = type;
             return obj;
         }
     }).on("fileuploaded", function (event, data, previewId, index) {    	 
         $(".file-preview-initial").css({
             'display':'none'
         });
         $('#userTable').bootstrapTable("refresh");
    }).on('filepreupload', function(event, data, previewId, index) {  //批量成功后的回调函数
        $("#bootstraptable_fishcontent").bootstrapTable("refresh");
       /* $(".file-preview-frame.krajee-default.file-preview-initial.file-sortable.kv-preview-thumb").css({
            'display':'none'
        });*/
        /*$(".file-preview-frame,.krajee-default,.file-preview-initial,.file-sortable,.kv-preview-thumb").hide();*/
    	$('#userTable').bootstrapTable("refresh");
    });
  };

后端需要写一个config类,因为修改图片和预览图片的时候需要回显图片,而回显图片不在静态资源目录下需要配置虚拟映射路径。
如下将/image和/imgs配置为虚拟路径,配置好之后,在页面加载图片的时候写虚拟路径就可以。

@Configuration
@ConfigurationProperties(prefix = "image")
public class MyWebConfig implements WebMvcConfigurer{

	@Value("${image.virtualLocation}")
	private String virtualLocation;
	
	@Value("${image.defaultLocation}")
	private String defaultLocation;
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
	    registry.addResourceHandler("/imgs/**").addResourceLocations(defaultLocation);
	    registry.addResourceHandler("/image/**").addResourceLocations(virtualLocation);
	    //registry.addResourceHandler("/image/**").addResourceLocations("file:///usr/local/jq/");
	}
}

修改图片的Controller关键代码如下,操作是将数据库中要修改的图片信息更新为修改之后的,并且删除服务器中的原图片,将新图片上传。

	@PostMapping("sys/updatePhotoPost")
    @ResponseBody
    public Map<String,String> updatePhoto(HttpServletRequest request,@RequestParam MultipartFile[] files,@RequestParam String productId,@RequestParam String shopId,@RequestParam String ids,@RequestParam String type) throws Exception{
    	int idsInt = Integer.parseInt(ids);//要修改的图片的编号
		int shopIdInt = Integer.parseInt(shopId);
		int productIdInt;
		int delectNum = 0;
		//通过id去删除这条数据
		PhotoInfo pi = iPhotoInfoService.findPhotoById(idsInt);
    	//String filePath = request.getSession().getServletContext().getRealPath("") + pi.getUploadLocation();
		String filePath =pi.getUploadLocation();
    	boolean delete_flag = false;
		File fil = new File(filePath);
		if (fil.exists() && fil.isFile() && fil.delete()) {
			delete_flag = true;
		} else {
        	delete_flag = false;
		};
		/*if(delete_flag) {
			delectNum = iPhotoInfoService.delectPhotoById(idsInt);
		}
*/
		delectNum = iPhotoInfoService.delectPhotoById(idsInt);
		for (MultipartFile file : files) {
            //根据时间戳创建新的图片名,这样即便是第二次上传相同名称的图片,也不会把第一次的图片覆盖了			
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的图片名
            String destFileName =request.getSession().getServletContext().getRealPath("") +  uploadLocation + File.separator + fileName;
            String uploadUrl = uploadLocation + File.separator + fileName;
            //第一次运行的时候,这个图片所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
            //File destFile = new File(destFileName);
            try {
				File destFile = new File(destFileName);
				if(!destFile.getParentFile().isDirectory()) {
					destFile.getParentFile().mkdirs();
				}      
				//把浏览器上传的图片复制到希望的位置
				file.transferTo(destFile);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            //查询景点名称
            String shopName = iPhotoInfoService.findShopInfoName(shopIdInt);
            //业务代码已删除                     
		}
		Map<String, String> map = new HashMap<String,String>();
        map.put("productId", productId);
        map.put("shopId", shopId);
        return map;
    }
}
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐