@RequestMapping("/xxx")
@ResponseBody
public void add(@RequestParam(“musicData”) MultipartFile file,@RequestParam(“lyricData”) MultipartFile file2,@RequestParam(“headData”) MultipartFile headData,HttpServletRequest request) throws IOException {
log.info(“进入添加音乐控制层”);
//获得session中的用户对象
Consumer consumer = (Consumer)request.getSession().getAttribute(“consumer”);
//文件名
String mName = file.getOriginalFilename();
String lName = file2.getOriginalFilename();
String hName = headData.getOriginalFilename();
// 设置要生成的文件地址
String musicPath =“d:\music\” + mName;
String lyricPath =“d:\lyric\” + lName;
String mHeadPath =“d:\img\” + hName;
//转换文件
File music = new File(musicPath);
File lyric = new File(lyricPath);
File mHead = new File(mHeadPath);
log.info(“添加音乐”);
//原文件存在,判断目标文件是否存在
if(!music.exists()){
//目标文件不存在,创建目标文件
music.getParentFile().mkdirs();
music.createNewFile();
}
//try catch
file.transferTo(music);
if(!lyric.exists()){
//目标文件不存在,创建目标文件
lyric.getParentFile().mkdirs();
lyric.createNewFile();
}
file2.transferTo(lyric);
if(!mHead.exists()){
//目标文件不存在,创建目标文件
mHead.getParentFile().mkdirs();
mHead.createNewFile();
}
headData.transferTo(mHead);
//后面可以调用service进行存入musicPath 等
(上边转换最好捕获一下异常,简单的写法,但是也实现了功能)
}
附上一段读取
@RequestMapping("selectMusicData")
@ResponseBody
public byte[] selectMusicData(Integer mId,HttpServletRequest request) throws IOException {
byte[] data = null;
log.info("进入音乐控制器 的 selectById 方法");
log.info("入参 mId;{}",mId);
CloudmusicWithBLOBs cloudmusicWithBLOBs = service.selectById(mId);
//获得数据地址
String musicData = cloudmusicWithBLOBs.getMData();
try {
File file = new File(musicData);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*16);
byte[] b = new byte[1024*16];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
//获得数据流
data = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
return data;
}
}