springboot 整合文件上传

package wwfww.warehouse.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import wwfww.warehouse.base.XCoreResult;
import wwfww.warehouse.base.XCoreResultGenerator;
import wwfww.warehouse.util.IdentityIdGenerator;
import wwfww.warehouse.util.UUIDGeneratorUtil;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.*;

/**
 * @版权:版权所有 (c) 2017
 * @author:cwj
 * @version Revision 1.0.0
 * @email:cwjie@betterda.com
 * @see:
 * @创建日期:2019年11月25日 @功能说明: @begin
 * @修改记录:
 * @修改后版本 修改人 修改内容
 * @2019年5月23日 cwj 创建
 * @end
 */
@Slf4j
@Api(tags = "上传模块")
@RestController
@RequestMapping(value = "api/upload")
@MultipartConfig
public class UploadPicturesController {
	/**
	 * @param
	 * @return
	 * @author:liuyu
	 * @email:lyu@betterda.com
	 * @创建日期:2020年3月5日
	 * @功能说明:上传图片(可以给app用)
	 */
	@ApiOperation(value = "上传图片", notes = "上传图片")
	@PostMapping(value = "uploadImage")
	public XCoreResult<String> uploadImage(HttpServletRequest request) {
		try {
			Part part = request.getPart("file");
			String suffix = getFileSuffix(part);
			String path = writeTo(part,suffix);

			return XCoreResultGenerator.success(path);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return XCoreResultGenerator.error(e.getMessage());
		}
	}
	private String getFileSuffix(Part part) {
		  String head = part.getHeader("Content-Disposition");
		  String fileName = head.substring(head.indexOf("filename=\"")+10, head.lastIndexOf("\""));
		  System.out.println(fileName);
		  return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		}
	
	private String writeTo(Part part, String suffix)throws IOException {
		File newfile = new File("D:\\image");
		if (!newfile.exists()) {
			newfile.mkdirs();
		}
		String newurl = "/"+ UUIDGeneratorUtil.buildMallOrderSn()+".jpg";
	    InputStream in = part.getInputStream();
		OutputStream out = new FileOutputStream(newfile+newurl);
		 byte[] b = new byte[1024];
		  int length = -1;
		    while((length = in.read(b))!=-1){
		    out.write(b, 0, length);
		  }
		  in.close();
		  out.close();
		return "upload"+newurl;
		}
	/**
	 * @param
	 * @return
	 * @创建日期:2020年3月5日
	 * @功能说明:上传文件,可以是图片可以是tex等等文件
	 */
	@ApiOperation(value = "上传文件(1M)")
	@PostMapping(value = "upload")
	public XCoreResult<String> upload(@ApiParam(value = "文件", required = true) MultipartFile file) {
		try {
			String fileName = file.getOriginalFilename();
			String suffix = StringUtils.substringAfterLast(fileName, ".");
			String uuid = String.valueOf(String.valueOf(IdentityIdGenerator.getFlowIdInstance().nextId()));
			String newFileName = uuid + "." + suffix;
			//保存文件的路径
			File newfile = new File("D:\\image\\" + uuid + "\\");
			//判断是否存在文件夹,不存在则创建,exists()用来判断文件夹是否存在,mkdirs()是创建文件夹
			if (!newfile.exists()) {
				newfile.mkdirs();
			}
			//保存文件
			file.transferTo(new File(newfile + "\\" + newFileName));
			return XCoreResultGenerator.success("成功", newFileName);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return XCoreResultGenerator.failure("失败");
		}
	}
}

upload方法默认文件大小是1M,要改变上传大小的话,修改yml配置文件

spring:
  servlet:
    multipart:
      enabled: true
      #设置单个文件上传大小限制
      max-file-size: 10MB
      #设置文件上传的总容量
      max-request-size: 100MB

如果写配置不好用的话,也可以编写配置bean

@Configuration
public class UploadConfig {
    /**
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大
        factory.setMaxFileSize(DataSize.parse("100MB"));
        // 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("100MB"));
        return factory.createMultipartConfig();
    }
 
}
在Spring Boot中,你可以使用COS(腾讯云对象存储)来实现文件上传。以下是一个简单的示例: 1. 首先,需要在pom.xml文件中添加COS SDK的依赖: ```xml <dependency> <groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId> <version>5.6.9</version> </dependency> ``` 2. 在application.properties(或application.yml)文件中配置COS的相关信息: ```properties # COS配置 cos.secretId=your_secret_id cos.secretKey=your_secret_key cos.bucketName=your_bucket_name cos.region=your_bucket_region ``` 3. 创建一个文件上传的Controller: ```java import com.qcloud.cos.COSClient; import com.qcloud.cos.model.PutObjectRequest; import com.qcloud.cos.model.PutObjectResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @RestController public class FileUploadController { @Value("${cos.secretId}") private String secretId; @Value("${cos.secretKey}") private String secretKey; @Value("${cos.bucketName}") private String bucketName; @Value("${cos.region}") private String region; @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "请选择要上传的文件"; } try { // 创建COSClient实例 COSClient cosClient = new COSClient(secretId, secretKey); // 设置存储桶所在的地域 cosClient.setRegion(region); // 生成文件在COS中的唯一键 String key = file.getOriginalFilename(); // 创建上传请求 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(), null); // 执行上传操作 PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); // 关闭COSClient cosClient.shutdown(); return "文件上传成功,COS对象键:" + putObjectResult.getKey(); } catch (IOException e) { e.printStackTrace(); } return "文件上传失败"; } } ``` 以上示例代码中,`cos.secretId`、`cos.secretKey`、`cos.bucketName`和`cos.region`分别对应COS的SecretId、SecretKey、Bucket名称和Bucket所在的地域。你需要将这些值替换为你自己的配置。 4. 启动Spring Boot应用程序,并通过POST请求将文件发送到`/upload`路由。 这样,你就可以通过Spring Boot将文件上传到COS了。请确保已正确配置COS的访问权限和相关配置信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值