文件下载回显

首先思路是给前端一个url(里面的动作是赋值输出流)

1.上传byte[]

public byte[] uploadbyte(MultipartFile[] files, MarketChannelSaveRequest saveRequest, HttpServletRequest request) {
String listFileStr = "";
try {
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
String hexString = byteToHex(bytes);
listFileStr += fileName + "=" + hexString + ",";
}
listFileStr = listFileStr.substring(0, listFileStr.length() - 1);
} catch (IOException e) {
e.printStackTrace();
}
return ZipUtil.gzip(listFileStr, "UTF-8");
}
//转16进制 方便存储
public String byteToHex(byte[] buf) {
StringBuilder sb = new StringBuilder(buf.length * 2);
for (byte b : buf) {
sb.append(String.format("%02x", new Integer(b & 0xff)));
}
return sb.toString();
}
2.获取byte
public String download(String id) {
MarketChannel marketChannel = marketChannelDao.queryById(id);
String listFileStrs = ZipUtil.unGzip(marketChannel.getEmailAttachment(),"UTF-8");
return listFileStrs;

}
获取文件名和id byte
  String listFileStrs = this.download(channelId);
String[] bytesStrs = listFileStrs.split(",");
for (int i = 0; i < bytesStrs.length; i++) {
ShowBackResponse showBackResponse = new ShowBackResponse();
String[] files = bytesStrs[i].toString().split("=");
String fileName = files[0];
String byteStr = files[1];
showBackResponse.setName(fileName);
showBackResponse.setId(channelId);
appPushShowBackResponses.add(showBackResponse);
}
}
return appPushShowBackResponses;
回显 注 先赋值contentType 强制为下载 后赋值为直接展示
String channelId = id;
String listFileStrs = this.download(channelId);
String[] bytesStrs = listFileStrs.split(",");
for (int i = 0; i < bytesStrs.length; i++) {
String[] files = bytesStrs[i].toString().split("=");
String fileName = files[0];
if(fileName.equals(name)){
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
String byteStr = files[1];
byte[] bytes= this.hexToByteArray(byteStr);
outputStream.write(bytes);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
//outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}else {
continue;
}
}
16进制转回2进制
/**
* hex字符串转byte数组
* @param inHex 待转换的Hex字符串
* @return 转换后的byte数组结果
*/
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=hexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}

/**
* Hex字符串转byte
* @param inHex 待转换的Hex字符串
* @return 转换后的byte
*/
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}

文件下载回显

上一篇:DNN中的Sparsity研究


下一篇:idea 导包 同属一个包的类用*替代