前后端分离,浏览器上传下载文件

服务器文件浏览器下载:
vue请求:

downloadService(){
this.$confirm('确认要下载吗?', '提示', {
confirmButtonText: '确认',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
window.open(encodeURI( restoreService.geturl()+
'/asd/dasd?dsad))
window.close()
}).catch(() => {
this.$message({
type: 'info',
message: '已取消'
});
})

},

 

//后端请求:

public ResponseEntity<byte[]> simpleExport() throws BackupsException {

try {

String filename = path+ name;
FileObject fileObject = new FileObject();
fileObject = buildFileObject(fileObject, filename, name,contentsProj);
return download(fileObject);

} catch (Exception e) {
e.printStackTrace();
msg = "Error:服务备份失败";
msgError = msg;
}

}

public static FileObject buildFileObject(FileObject fileObject, String fileName, String exportFileName,byte[] data) {
FileInputStream is = null;
FileOutputStream out = null;
try {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
out = new FileOutputStream(file);
out.write(data, 0, data.length);
is = new FileInputStream(new File(fileName));
fileObject.setStream(is);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(out != null)
try {
out.close();
} catch (IOException e) {
}
}
fileObject.setId("2");
fileObject.setName(exportFileName);
fileObject.setSize(10000000);
fileObject.setType(".jar");
return fileObject;
}

public static ResponseEntity<byte[]> download(FileObject fo) throws UnsupportedEncodingException, IOException {
return download(fo.getName(), fo.getStream());
}

public static ResponseEntity<byte[]> download(String name, InputStream fis) throws UnsupportedEncodingException, IOException {
HttpHeaders headers = new HttpHeaders();
// String Agent = WebUtils.getRequest().getHeader("User-Agent");
/*if (null != Agent) {
Agent = Agent.toLowerCase();
if (Agent.indexOf("Mozilla") != -1) {
name = new String(name.getBytes(),"iso8859-1");
} else {
name = java.net.URLEncoder.encode(name,"UTF-8");
}
}*/
name = new String(name.replaceAll(" ", "").getBytes("gb2312"),"ISO_8859_1");
headers.setContentDispositionFormData("attachment", name);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.set("X-fileName", name);
byte[] bytes = input2byte(fis);
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}

public static final byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
// swapStream.close();
return in2b;
}

 

浏览器上传文件到服务器:

vue请求:

uploadFile(params) {
this.loading = true
const _file = params.file;
// const isLt2M = _file.size / 1024 / 1024 < 2;
// 通过 FormData 对象上传文件
var formData = new FormData();
formData.append("file", _file);
// if (!isLt2M) {
// this.$message.error("请上传2M以下的.xlsx文件");
// return false;
// }
this.$axios.post(restoreService.geturl() +'/asd/sdf?we',formData,{ headers : { 'Content-type':'multipart/form-data'}}).then(res => {
if (res.data.status === '200') {
this.$message({
type: 'success',
message: res.data.message,
})
} else {
this.$message({
type: 'warning',
message: res.data.message
})
}
this.$refs.upload.clearFiles();
this.loading = false
})
},

//后端请求:

@RequestMapping(value = "/Import", method = RequestMethod.POST)
public BaseResult<BackUpDto> simpleImport(@RequestParam(value = "file") MultipartFile file) throws Exception {
return logBackupRestoreService.simpleImport(file.getInputStream());
}

public BaseResult<BackUpDto> simpleImport(InputStream inputStream) throws BackupsException {
String path = System.getProperty("user.dir");
String fileGuid = UUID.randomUUID().toString();
File file = new File(path + "\\" + fileGuid + ".tmp");
byte[] bytes = null;
try {
bytes = inputStreamToFile(inputStream, file);
} catch (Exception e) {

}

}

public static byte[] inputStreamToFile(InputStream ins, File file) throws Exception{
ByteArrayOutputStream ous = null;
// OutputStream os = null;
try {
// os = new FileOutputStream(file);
ous = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
ous.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
// logger.error(e.getMessage(), e);
throw new Exception(e);
}finally{
if(ous != null){
ous.close();
}
if(ins != null){
ins.close();
}

}
return ous.toByteArray();
}



 

转载于:https://www.cnblogs.com/js1314/p/10789021.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值