上传文件到数据库

上传文件到MySQL数据库

后端

@Login
	@ResponseBody
	@RequestMapping(value="/uploadfj",produces="text/html; charset=utf-8")
	@Transactional
	public String uploadxdwlfile(HttpServletResponse response,HttpServletRequest request, ModelMap model,@RequestParam String projectId, @RequestParam String filetype ,@RequestParam String filecode) throws Exception{
		XdwlzxfjFile xdwlzxfjFile = new XdwlzxfjFile(); //接受文件的Javabean
		xdwlzxfjFile.setFilecode(filecode);  //文件的唯一标识    uuid
		xdwlzxfjFile.setFlietype(filetype); //文件的类型
		xdwlzxfjFile.setProjectid(projectId); //  文件关联的主键id
		if(materialflowMapper.getXdwlzxfjFile(xdwlzxfjFile) != null) {
			materialflowMapper.deleteXdwlzxfjFile(xdwlzxfjFile);
		}
		SystemConfig config = new SystemConfig();
		String  maxsize="3000000";
		String suffix="JPG,GIF,PNG,TIF,DOC,DOCX,PDF,RAR,ZIP";
		maxsize = config.get("fgw.attachment.maxsize");
	    suffix=config.get("fgw.attachment.suffix");
	    HttpHeaders headers = new HttpHeaders();
	    headers.setContentType(new MediaType("text", "plain",  Charset.forName("UTF-8")));		
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
		 if(multipartResolver.isMultipart(request)) {
			 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
			 Iterator<String> iter = multiRequest.getFileNames(); 
			 if(iter.hasNext()) {
				 MultipartFile file = multiRequest.getFile(iter.next());
				 if(file != null) {
					 String myFileName = file.getOriginalFilename();//文件名
					 Long size=file.getSize();
                     Long maxsize1=Long.parseLong(maxsize);
                     String [] suffixs=suffix.split(",");
                     boolean bsuffix=true;
                     for(String item:suffixs){
                    	 String as=myFileName.toUpperCase();
                    	int i=as.indexOf(item.toString());
                    	if(i>-1){
                    		bsuffix=false;
                    		break;
                    	}
                     }
                     if(bsuffix){
                    	 String meg="文件支持类型为"+suffix+"!";
                    	 return  meg;
                     }else  if(size>maxsize1){
                    	 String meg="文件大小不能超过"+maxsize1/1024/1024+"M!";
                    	 return   meg; 
                     }else if(file.getOriginalFilename().length()>50){
                    	 String meg="文件名称长度不能超过50个字符";
                    	 return meg; 
                     }
                     if(myFileName.trim() !=""){  
                    	 xdwlzxfjFile.setFilename(myFileName); //文件名字
                    	 xdwlzxfjFile.setFilecode(UUID.randomUUID().toString()); // 文件的标识
                    	 xdwlzxfjFile.setFilecontent(FileCopyUtils.copyToByteArray(file.getInputStream())); //文件本身
                    	 String count = ((materialflowMapper.insertXdwlzxfjFile(xdwlzxfjFile) > 0)? "上传成功" : "上传失败");
                    	 return count;
                     }
					 
				 }
			 }
		 }
		return null;
	}

javabean

/**
 * 
 */
package com.netmarch.sbgl.sfgw.bean;

/**
 * @author zxj
 *
 * 2019年8月21日-上午9:14:55
 */
public class XdwlzxfjFile {
	
	private int id;
	private String projectid;
	private String filecode;
	private String filename;
	private byte[] filecontent;     //在mysql数据库中对应的字段属性是  mediumblob
	private String flietype;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getProjectid() {
		return projectid;
	}
	public void setProjectid(String projectid) {
		this.projectid = projectid;
	}
	public String getFilecode() {
		return filecode;
	}
	public void setFilecode(String filecode) {
		this.filecode = filecode;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public byte[] getFilecontent() {
		return filecontent;
	}
	public void setFilecontent(byte[] filecontent) {
		this.filecontent = filecontent;
	}
	public String getFlietype() {
		return flietype;
	}
	public void setFlietype(String flietype) {
		this.flietype = flietype;
	}
	


}

前段使用ajaxfileupload.js ,网上很多,自己下载一个

</head>
<body>
<input type="file" id="file" name="file" />
<input type="button" value="上传" onclick="uplaod()"/>



<script>


function uplaod(){
	var projectId = "11111";
	var filetype = "fp";
	var filecode = "aaa";
	var url = '/pndpcmater/uploadfj?projectId=' + projectId +'&filetype=' +filetype + '&filecode=' + filecode; 
	var gamefile = document.querySelector("#file").value;
	var file = "file";
if(!gamefile){ 
	layer.alert('请选择文件!');
		return false;
}
	$.ajaxFileUpload({ 
     url:url, 
     type:"post", 
     secureuri:false, 
     fileElementId:file, 
     dataType:"text",
     success:function(result)  {
    	 alert(上传成功);
    	 /* layer.alert(result,function(index){
				layer.closeAll();
              location.reload(); 
			}); */
		},error : function(){
			alert("error");
		}
});  
}
</script>
</body>
</html>
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了多种上传文件数据库的方式,其中比较常见的是将文件转换为字节数组或流,然后将其存储到数据库中。 以下是一种基于Spring Boot和MySQL的文件上传示例,将文件转换为字节数组并将其存储到数据库中: 1. 创建一个Spring Boot项目,并添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 创建一个文件上传的实体类,用于存储文件的相关信息,如文件名、文件类型、文件内容等: ``` @Entity @Table(name = "files") public class FileEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String type; @Lob @Column(nullable = false) private byte[] content; // getters and setters } ``` 3. 创建一个文件上传的控制器,用于处理上传文件的请求: ``` @RestController @RequestMapping("/api/files") public class FileController { @Autowired private FileRepository fileRepository; @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { try { // 将文件转换为字节数组 byte[] content = file.getBytes(); // 创建一个FileEntity对象,设置文件相关信息 FileEntity fileEntity = new FileEntity(); fileEntity.setName(file.getOriginalFilename()); fileEntity.setType(file.getContentType()); fileEntity.setContent(content); // 将FileEntity对象保存到数据库中 fileRepository.save(fileEntity); return ResponseEntity.ok("File uploaded successfully!"); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file"); } } } ``` 4. 创建一个文件上传的存储库,用于与数据库交互: ``` @Repository public interface FileRepository extends JpaRepository<FileEntity, Long> { } ``` 5. 在应用程序的配置文件中,设置数据库连接信息: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update ``` 6. 启动应用程序,使用Postman或其他工具发送文件上传请求,测试上传功能。 以上就是一个基于Spring Boot和MySQL的文件上传数据库的示例。你可以根据需要进行修改和扩展,以适应自己的应用场景。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值