这是 Azure blob 存储容器为私有级别访问时在浏览器(PPTX、XLXS、XLS、PPT、DOC、DOCX)和 PDF 中预览 Office 文档的示例代码。
private static string GetContainerSharedAccessSignature(CloudBlockBlob blob, string fileName)
{
string contentType = "";
var headers = new SharedAccessBlobHeaders
{
ContentDisposition = $"attachment;filename={fileName}",
};
if (fileName.Contains(".xlsx"))
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
else if (fileName.Contains(".docx"))
contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
else if (fileName.Contains(".pptx"))
contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
else if (fileName.Contains(".doc"))
contentType = "application/msword";
else if (fileName.Contains(".xls"))
contentType = "application/vnd.ms-excel";
else if (fileName.Contains(".ppt"))
contentType = "application/vnd.ms-powerpoint";
else if (fileName.Contains(".rtf"))
contentType = "application/rtf";
else if (fileName.Contains(".jpg"))
contentType = "image/jpg";
else if (fileName.Contains(".jpeg"))
contentType = "image/jpeg";
else if (fileName.Contains(".png"))
contentType = "image/png";
else if (fileName.Contains(".gif"))
contentType = "image/gif";
else if (fileName.Contains(".bmp"))
contentType = "image/bmp";
else if (fileName.Contains(".tif"))
contentType = "image/tif";
else
contentType = "application/octet-stream";
if (!string.IsNullOrWhiteSpace(contentType))
{
headers.ContentType = contentType;
}
var signature =
blob.GetSharedAccessSignature(
new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.Now.AddMinutes(10)
},
headers);
return Uri.EscapeDataString($"{blob.StorageUri.PrimaryUri.AbsoluteUri}{signature}");
}
public string GenerateSASToken(string containerName, string fileName)
{
CloudBlobContainer cloudBlobContainer = null;
try
{
CloudBlobClient cloudBlobClient = searchConfig.CloudBlobClient;
cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);
var blob = cloudBlobContainer.GetBlockBlobReference(fileName);
return GetContainerSharedAccessSignature(blob, fileName);
}
catch (Exception)
{
throw;
}
}
[HttpGet("bloburl/{fileName}/{container}")]
public IActionResult BlobSASTokenURL(string fileName, string container)
{
try
{
if (string.IsNullOrEmpty(fileName))
{
_logger.Log(LogLevel.Warning, $"file name {fileName} is missing.");
return UnprocessableEntity();
}
if (string.IsNullOrEmpty(container))
{
_logger.Log(LogLevel.Warning, $"container name {fileName} is missing.");
return UnprocessableEntity();
}
var tokenUrl = blobStorageService.GenerateSASToken(container, fileName);
var token = new { tokenUrl };
return Ok(token);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, $"Failed to generate token url for {fileName} .");
}
}
前端
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class SearchService {
public getBlobSASUrl(fileName: string, containerName: string): Observable<any> {
return this.repository.get(environment.apiBaseURL, 'api/BlobStorage/sastoken/' + fileName + '/' + containerName)
.pipe(map((res: any) => {
return res.tokenUrl;
}));
}}
零件
import { UrlService } from './shared/search.service';
@Component({
templateUrl: './filePreview.component.html',
styleUrls: [],
providers: [ DatePipe ]
})
export class filePreviewComponent implements OnInit {
constructor(private urlService: UrlService, public sanitizer: DomSanitizer, public datepipe: DatePipe) {
}
showFilePreview(fileName: string, containerName: string, fileContentType: string) {
this.urlService.getBlobSASUrl(result.document.fileName, result.document.containerName).subscribe(results => {
result.document.fileURL = this.sanitizer.bypassSecurityTrustResourceUrl('https://view.officeapps.live.com/op/embed.aspx?src='+results+'&embedded=true');
result.document.toggle =! result.document.toggle;
});
}
}
HTML
<div id="divpreview" class="preview_container_wrapper" *ngIf="result.document.toggle && result.document.containerName != null">
<div class="col-md preview_container" id="dvpreviewcol">
<iframe *ngIf="FileType !== 'PDF';"
[src]='fileURL'
class="preview_iframe"></iframe>
<object *ngIf="FileType === 'PDF';" [data]="fileURL | safeUrl" type="application/pdf">Preview not available</object>
</div>
</div>