需求可以不看
需求:
接到需求是:前端传一个id,根据id去数据库里找图片保存地址,图片真实路径,和数据库保存路径不一致,所以路径要自己拼接。
这是真实图片路径
数据库存储路径 
可看出后缀不一样,大小写没关系

测试又多了个前缀
一、下载图片到本地
1.直接上代码
import cn.hutool.core.lang.UUID;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import lombok.SneakyThrows;
import com.egao.common.core.exception.BusinessException;
import java.io.*;
@SneakyThrows
@Override
public void downLoadPanorama(String id) {
//根据前端传的id去数据库找对应图片信息
Panorama panorama = panoramaDao.selectById(id);
//获取图片地址
String bImageNew = panorama.getBImageNew();
//截取掉..
String substring = bImageNew.substring(2);
//截取最后一个\\之前的路径
String s = org.apache.commons.lang3.StringUtils.substringBeforeLast(substring, "\\");
//设置后缀
String suffix = "\\pano.JPG";
//由于string拼接效率较低,换种玩法
StringBuilder builder = new StringBuilder();
//数据库的路劲不对,要组装路径
builder.append("src\\main\\resources\\static\\panorama").append(s).append(suffix);
FileInputStream inputStream = null;
try{
inputStream = new FileInputStream(String.valueOf(builder));
}catch (Exception e){
throw new BusinessException("图片不存在");
}
StringBuffer stringBuffer = new StringBuffer();
//组装下载路径,利用uuid可以重复下载多次,防止覆盖
StringBuffer downLoadPath = stringBuffer.append("E:\\").append(java.util.UUID.randomUUID().toString()).append(".jpg");
File file = new File(String.valueOf(downLoadPath));
if(!file.exists()){
file.createNewFile();
}
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new BusinessException("图片太大");
}
byte[] bytes = new byte[1024];
int length;
while((length=inputStream.read(bytes)) !=-1){
outputStream.write(bytes);
}
outputStream.close();
inputStream.close();
}
2.测试如下
重复下载:
@RunWith(SpringRunner.class)
@SpringBootTest
public class RGisApplicationTests {
@Resource
private PanoramaService panoramaService;
@Test
public void text() {
panoramaService.downLoadPanorama("fh-620326c7bfca2552486f3bd9");
}
}
总结
接到这个新功能,经过分析、查资料、调试、最终呈现出来的效果。
根据不同的业务场景,逻辑可能稍有变动,核心代码不变。
1万+

被折叠的 条评论
为什么被折叠?



