CDN is installed in Local FTP Server. I want to upload file to it but it gets the file path wrong. I think it is due to Handler but I couldn't find the error.
File Upload;
public static class FileUpload
{
public static string ImageUpload(this IFormFile file, string path)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(@"cdnadress" + "/" + Path.GetFileName(path));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
//Load the file
FileStream stream = File.OpenRead(path);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
request = null;
return null;
}
CreateHandler;
public class SliderCreateHandler : IRequestHandler<SliderCreate, ApiResponse<SliderResponse>>
{
private readonly IUnitOfWork _repo;
private readonly IMapper _mapper;
public SliderCreateHandler(IUnitOfWork repo, IMapper mapper)
{
_repo = repo;
_mapper = mapper;
}
public async Task<ApiResponse<SliderResponse>> Handle(SliderCreate request, CancellationToken cancellationToken)
{
var mapped = _mapper.Map<Slider>(request);
mapped.ImageUrl = request.file.ImageUpload(Environment.CurrentDirectory+ @"\Image\Slider\");
if (string.IsNullOrEmpty(mapped.ImageUrl))
return new ErrorApiResponse<SliderResponse>(ResultMessage.UnsupportedFileType);
if (mapped == null)
return new ErrorApiResponse<SliderResponse>(ResultMessage.NotCreatedSlider);
var model = await _repo.Sliders.AddAsync(mapped);
var response = _mapper.Map<SliderResponse>(model);
return new SuccessApiResponse<SliderResponse>(response);
}
}
Here is the error id. I was racing on this road somewhere or I missed it. Can you help me?
If your goal was to upload the IFormFile
then:
IFormFile.CopyTo
to access the file contents. It's all in-memory data. There are no physical paths/files involved.IFormFile.FileName
to find the name of the file. Some fallback name is recommendable, as the browser might not provide one.FtpWebRequest request =
(FtpWebRequest)FtpWebRequest.Create(@"cdnadress" + "/" + file.FileName);
// rest of your FtpWebRequest setup here
using (Stream reqStream = request.GetRequestStream())
{
file.CopyTo(reqStream);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.