我非常喜欢aspnetboilerplate框架,我现在正在学习/使用它。
如何在AppServices for aspnetboilerplate中执行'文件上传'逻辑/方法?我想出了角度部分并且工作正常。
如何编写在appservice层中接收文件上传的方法?关于crud有很好的例子,并且昂首阔步。现在我想实现文件上传。这在appservice层中是否可行,或者我是否必须在控制器方法中执行此操作?
答案 0 :(得分:0)
通过ApplicationServices无法做到这一点。您需要在Web项目中使用MVC控制器和操作执行此操作,就像在常规项目中执行此操作一样。如果您需要更多帮助,我可以提供帮助。
答案 1 :(得分:0)
所有应用程序服务都可以访问HttpContext对象,因此它们也能够处理文件上载。将文件上传到应用程序。 service确保使用正确的url +标头。
应用。服务示例:
public class MyUploadService : MyApplicationBaseClass, IMyUploadService
{
/// <summary>
/// References the logging service.
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Construct an new instance of this application service.
/// </summary>
public MyUploadService(ILogger logger)
{
_logger = logger;
}
/// <summary>
/// Method used to handle HTTP posted files.
/// </summary>
public async Task Upload()
{
// Checking if files are sent to this app service.
if(HttpContext.Current.Request.Files.Count == 0)
throw new UserFriendlyException("No files given.");
// Processing each given file.
foreach(var file in HttpContext.Current.Request.Files)
{
// Reading out meta info.
var fileName = file.fileName;
var extension = Path.GetExtension(file.FileName);
// Storing file on disk.
file.SaveAs("~/uploads");
}
}
}
答案 2 :(得分:0)
我们实现文件上传方法: - 使用sql server fileTable技术 - 实现应用程序方法的服务以接受类似于此Dto的数据
public FileDto File { get; set; }
...
public class FileDto
{
public FileDto()
{
}
public FileDto(string file, string fileType)
{
File = file;
FileType = fileType;
}
[DisableAuditing]
public string File { get; set; }
public string FileName { get; set; }
public Guid? StreamId { get; set; }
public string FileType { get; set; } = "";
[DisableAuditing]
public string FileWithHeader
{
get
{
if (FileType == null|| FileType=="")
return "";
if (FileType.ToLower() == "jpg" || FileType.ToLower() == "jpeg")
return "data:image/Jpeg;base64," + File;
if (FileType.ToLower() == "png")
return "data:image/png;base64," + File;
if (FileType.ToLower() == "gif")
return "data:image/gif;base64," + File;
if (FileType.ToLower() == "ppt")
return "data:application/vnd.ms-powerpoint;base64," + File;
if (FileType.ToLower() == "xls")
return "data:application/vnd.ms-excel;base64," + File;
if (FileType.ToLower() == "doc")
return "data:application/msword;base64," + File;
if (FileType.ToLower() == "zip")
return "data:application/zip;base64," + File;
if (FileType.ToLower() == "exe")
return "data:application/octet-stream;base64," + File;
if (FileType.ToLower() == "txt")
return "data:text/plain;base64," + File;
if (FileType.ToLower() == "pdf")
return "data:application/pdf;base64," + File;
if (FileType.ToLower() == "bmp")
return "data:image/bmp;base64," + File;
if (FileType.ToLower() == "csv")
return "data:text/csv;base64," + File;
if (FileType.ToLower() == "pptx")
return "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64," + File;
if (FileType.ToLower() == "xlsx")
return "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + File;
if (FileType.ToLower() == "docx")
return "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64," + File;
if (FileType.ToLower() == "rar")
return "data:application/x-rar-compressed;base64," + File;
if (FileType.ToLower() == "rtf")
return "data:application/rtf;base64," + File;
return "";
}
}
}
和方法实施
public UploadFileOutput UploadFile(UploadFileInput input)
{
if (input.Id <= 0 || input.File == null)
{
throw new UserFriendlyException(L("GetDataError"));
}
return new UploadFileOutput()
{
StreamId = _attachmentRepo.InsertAttachment(input.File.FileName, Convert.FromBase64String(input.File.File), LIMSConsts.HeightThumbnail, true, ServerConfig.ThumbnailImagePath),
};
}
insertAttachment方法:
public Guid InsertAttachment(string fileName, byte[] fileStream, int heightThumbnail = 50, bool saveThumbnail = false,string thumbLocationPath=null)
{
Guid AttachmentId = Guid.Empty;
SqlParameter _attachmentId = new SqlParameter();
_attachmentId.ParameterName = "@attachmentId";
_attachmentId.Direction = System.Data.ParameterDirection.InputOutput;
_attachmentId.Value = AttachmentId;
SqlParameter _fileStream = new SqlParameter();
_fileStream.SqlDbType = System.Data.SqlDbType.VarBinary;
_fileStream.Value = fileStream;
_fileStream.ParameterName = "@fileStream";
Context.Database.ExecuteSqlCommand("EXECUTE dbo.sp_AttachmentFile_Insert @AttachmentId OUTPUT,@fileName,@fileStream",
_attachmentId,
new SqlParameter("@fileName", fileName),
_fileStream);
if (saveThumbnail == true) {
var ms = new MemoryStream(fileStream);
var image = Image.FromStream(ms);
var width = (int)(heightThumbnail * image.Width / image.Height);
var height = (int)(heightThumbnail);
var Thumbnail = new Bitmap(width, height);
Graphics.FromImage(Thumbnail).DrawImage(image, 0, 0, width, height);
Bitmap Thumb= new Bitmap(Thumbnail);
Thumb.Save(Path.Combine(thumbLocationPath, _attachmentId.Value+".jpg"), ImageFormat.Jpeg);
}
return (Guid)_attachmentId.Value;
}
和存储过程实现
ALTER PROC [dbo].[sp_AttachmentFile_Insert]
@AttachmentId uniqueidentifier out,
@fileName nvarchar(256),
@fileStream VARBINARY(max)
AS SET @ AttachmentId = NEWID()
WHILE(EXISTS(SELECT 1 FROM dbo.Attachment WHERE name=@fileName))
BEGIN
DECLARE @fileExtention NVARCHAR(100)
SELECT @fileExtention ='.'+dbo.GetFileExtension(@fileName)
SET @fileName=REPLACE(@fileName,@fileExtention,'')+
CAST(DATEPART( DAY, GETDATE()) AS VARCHAR(10))+'_'
+CAST(DATEPART( HOUR, GETDATE()) AS VARCHAR(10))+'_'+
+CAST(DATEPART( MINUTE, GETDATE()) AS VARCHAR(10))+'_'+
+CAST(DATEPART( SECOND, GETDATE()) AS VARCHAR(10))+@fileExtention
END
INSERT into dbo.Attachment(stream_id,name,file_stream)
VALUES(@AttachmentId,@fileName,@fileStream)
最后感谢“HalilİbrahimKalkan”这个令人敬畏的框架。
答案 3 :(得分:0)
无法从Appservice上传文件,您需要使用特定方法创建一个Web Api控制器。
public class EntityImageController : AbpApiController
{
private IEntityImageAppService iEntityAppService;
public EntityImageController( IEntityImageAppService pEntityImgAppService ) : base()
{
this.LocalizationSourceName = AppConsts.LocalizationSourceName;
this.iEntityImgAppService = pEntityImgAppService;
}
[AbpAuthorize( PermissionNames.Entity_Update )]
[HttpPost]
public async Task<HttpResponseMessage> Set()
{
// Check if the request contains multipart/form-data.
if( !Request.Content.IsMimeMultipartContent() )
{
throw new HttpResponseException( HttpStatusCode.UnsupportedMediaType );
}
string root = HttpContext.Current.Server.MapPath( "~/App_Data" );
var provider = new MultipartFormDataStreamProvider( root );
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync( provider );
var mEntityId = provider.FormData[ "EntityId" ];
MultipartFileData mFileData = provider.FileData.FirstOrDefault();
var mFileInfo = new FileInfo( mFileData.LocalFileName );
var mImageBytes = File.ReadAllBytes( mFileInfo.FullName );
await this.iEntityImgAppService.Set( new EntityImageInput
{
ImageInfo = mImageBytes,
EntityId = Convert.ToInt32( mEntityId )
} );
return Request.CreateResponse( HttpStatusCode.OK );
}
catch( System.Exception e )
{
return Request.CreateErrorResponse( HttpStatusCode.InternalServerError, e );
}
}
}
答案 4 :(得分:0)
在web.core项目中创建文件上传控制器。 然后引用您的appService处理文件。
[HttpPost]
[AbpMvcAuthorize(PermissionNames.TenantPageJob)]
public async Task UploadExcelJobs()
{
var files = Request.Form.Files;
foreach (var file in files)
{
if (file.Length > 0 && file.ContentType.Contains("excel"))
{
var targetPath = Path.Combine(Path.GetTempPath(), (new Guid().ToString()), file.FileName);
var fs = new FileStream(targetPath, FileMode.OpenOrCreate);
await file.CopyToAsync(fs);
await _myAppService.ProcessFile(targetPath);
System.IO.File.Delete(targetPath);
}
}
}
答案 5 :(得分:0)
重点是如何从从ApplicationService派生的XXXAppService类的方法中获取文件,而不是从从AbpController或Microsoft.AspNetCore.Mvc.Controller派生的XXXController中获取文件。
所以您应该记住该类:HttpContext / HtttpRequest / HttpResponse !!!
解决方案:在类XXXAppService中注入httpContextAccessor即可实现。 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-5.0
这是我的代码,希望对您有帮助!
--------服务器端(ABP)--------------
[Route("api/")]
public class XXXAppService : ApplicationService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public XXXAppService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
[HttpPost, Route("upload")]
public void UploadFile()
{
var files = _httpContextAccessor.HttpContext.Request.Form.Files;
//do logics as you like here...
}
}
---(1)UI(PrimeNG上传组件)
<p-fileUpload name="demo[]" [multiple]="true" [url]="uploadUrl"
(onUpload)="onUpload($event)">
<ng-template pTemplate="content">
<ul *ngIf="uploadedFiles.length">
<li *ngFor="let file of uploadedFiles">{{file.name}} - {{file.size / 1000}}kb</li>
</ul>
</ng-template>
</p-fileUpload>
---(2)UI逻辑(组件)
import { AppConsts } from '@shared/AppConsts';
uploadUrl: string = '';
uploadedFiles: any[] = [];
ngOnInit() {
//http://localhost:21021/api/upload
let url_ = AppConsts.remoteServiceBaseUrl + "/api/upload";
this.uploadUrl = url_.replace(/[?&]$/, "");
}
onUpload(event: any) {
_.forEach(event.files, v => {
this.uploadedFiles.push(v);
});
}