Carga de imágenes basada en Maven (la ruta de la imagen se almacena en la base de datos)

Código de front-end:

<input type="file" id="file" name="file"/>

Use ajax para pasarlo al fondo (código ajax):


```css
file.onchange = function(){
    
    
	var formData = new FormData();
     var temp = file.files[0];
     if (temp){
    
    
                formData.append('file',temp)
                img.src = window.URL.createObjectURL(temp)
                $.ajax({
    
    
                    url:"/uploadImg/"+id,
                    type:"POST",
                    data: formData,
                    dataType : "json",
                    processData: false, // 告诉jQuery不要去处理发送的数据
                    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                    success: function(result){
    
    
                        //alert(result);
                        window.location.reload();
                    }
                });
            }

Código Java de fondo:


```java
@RequestMapping(value = "/uploadImg/{
    
    id}", method = RequestMethod.POST)
    public String upload(@RequestParam("file")MultipartFile file,Model model,
    		@PathVariable("id") int id,
            HttpServletRequest request) {
    
    
    	if (file.isEmpty()) {
    
    
            return "上传失败,请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String newName = null;
        System.out.println(fileName);
     // 生成uuid作为文件名称
     	String uuid = UUID.randomUUID().toString().replaceAll("-", "");
     	/*// 获得文件类型(可以判断如果不是图片,禁止上传)
     	String contentType = user.getFile().getContentType();*/
     	// 获得文件后缀名
     	String suffixName = fileName
     					.substring(fileName.indexOf("/") + 1);
     	// 得到 文件名
     	newName = uuid + "." + suffixName;
        File dest = null;
        String path = null;
        String os = System.getProperty("os.name");
        System.out.println(os);
        if (os.toLowerCase().startsWith("win")) {
    
    
            path = "E:"+File.separator+"test"+File.separator;
            System.out.println(path);
            dest= new File(path + newName);
        }else {
    
    
            path = "/webapps/img/";
            dest= new File(path + newName);
        }
        model.addAttribute("src","img/"+newName);
		try {
    
    
            file.transferTo(dest);
            //把评论插入数据库
            Comment comment=new Comment();
            comment.setImages(newName);//此处只给出了images属性
            commentMapper.insert(comment);
            return JSON.toJSONString("上传成功!");
        } catch (IOException e) {
    
    
        	return JSON.toJSONString("上传失败!");
        }
    }

¡En este punto, podemos subir fotos!

Supongo que te gusta

Origin blog.csdn.net/lq1759336950/article/details/106573831
Recomendado
Clasificación