我使用表单fileData:
将图像上传到服务器[Route("upload")]
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
try
{
if (!Request.Content.IsMimeMultipartContent()) {
Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var provider = GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
//Get Album name from Form
var titleOfAlbum = GetTitleOfAlbum(provider);
//get path to file
var pathToCoverDecoded = result.FileData.First().LocalFileName;
//Encodeing to base 64 path
var bytes = Encoding.UTF8.GetBytes(pathToCoverDecoded);
var base64 = Convert.ToBase64String(bytes);
Album al = new Album();
al.Title = titleOfAlbum;
al.PathToCover = base64;
db.Albums.Add(al);
db.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
private string GetDesereleazedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
private string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
private MultipartFormDataStreamProvider GetMultipartProvider()
{
var uploadFolder = HttpContext.Current.Server.MapPath("~/Files");
if (Directory.Exists(uploadFolder) == false)
{
Directory.CreateDirectory(uploadFolder);
}
return new MultipartFormDataStreamProvider(uploadFolder);
}
private string GetTitleOfAlbum(MultipartFormDataStreamProvider provider)
{
var titleOfAlbum = "";
foreach(var key in provider.FormData.GetValues(0))
{
titleOfAlbum = key;
}
return titleOfAlbum;
}
}
路径看起来像:
&#34; C:\ Users \ Oops \ Documents \ Visual Studio 2015 \ Projects \ WebApplication1 \ ForMyCustomers \ WebApplication1 \ Files \ BodyPart_b40d80c5-47dc-41db-8e35-9d39d4e27939&#34;
并将其转换为base64,但它不会显示在页面上 我找不到文件错误。 我该如何解决?如果URL错误,我怎么能得到正确的?
答案 0 :(得分:1)
You cannot use physical path (the one you used) on web. The physical path like "C:\something" is the path that can be used only by your OS.
The URL however, is the path that you need and to use and to do that you need to put your files somewhere that is readable by your host (IIS).
You are already writing your files in "~/Files". so you just need to add the file name at the end.
var url= "~/Files/"+filename;
you need to save the file name when you are uploading your file so when you want to fetch data from DB, fetch the file name from DB and create the url using that.