接受发布的文件
Accept a POSTED file
我正在尝试使用 Angular 上传 PDF 8. 我正在成功获取用户在前端选择的文件。我正在将一些东西传递给后端,但是当我尝试从内存流中读取文件时,在将其转换为字符串的测试过程中,我得到了“[object FileList]”而不是文件的内容。
这是我不熟悉的swagger吗?我想我可能比以前更困了。
下面是我HTML选择的文件。
<div>
<form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">
<div>
<!-- TODO: rename profile -->
<input type="file" name="profile" (change)="onFileSelect($event)"
accept=".pdf"/>
</div>
<div>
<button type="submit">Upload</button>
</div>
</form>
</div>
下面是我的打字稿:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
@Component({
selector: 'app-pdf',
templateUrl: './pdf.component.html',
styleUrls: ['./pdf.component.css']
})
export class PDFComponent implements OnInit {
SERVER_URL = "http://localhost:64528/api/uploadPDF";
uploadForm: FormGroup;
file;
constructor(private formBuilder: FormBuilder, private httpClient: HttpClient) { }
ngOnInit() {
this.uploadForm = this.formBuilder.group({
profile:['']
});
}
onFileSelect(event){
var file = event.target.files;
if(file.length > 0){
this.file = event.target.files[0];
this.uploadForm.get('profile').setValue(file);
var confirm = this.uploadForm.get('profile').value;
}
}
onSubmit(){
const formData = new FormData();
formData.append('file', this.uploadForm.get('profile').value);
this.httpClient.post<any>(this.SERVER_URL, formData).subscribe(
(res) => console.log(res),
(err) => console.log(err)
);
}
}
下面是我的 C#
using HeadcountTrackingAPI.Repositories;
using HeadcountTrackingAPI.Utilities;
using Swashbuckle.Swagger.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace HeadcountTrackingAPI.Controllers
{
public class PDFController : ApiController
{
// GET api/<controller>
[SwaggerOperation("uploadPDF")]
[HttpPost]
[Route("api/uploadPDF")]
public async Task<IHttpActionResult> UploadFile()
{
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
// Initialize the memorty stream provider
MultipartMemoryStreamProvider memoryStream = new MultipartMemoryStreamProvider();
// Assign it's contents
memoryStream = await Request.Content.ReadAsMultipartAsync();
// Read the contents asynchronosly
using (System.IO.Stream pdfStream = await memoryStream.Contents.First().ReadAsStreamAsync())
{
byte[] bytes = new byte[pdfStream.Length];
// streamBytes to the byte array starting a position 0 and ending at the end of the file
pdfStream.Read(bytes, 0, (int)pdfStream.Length);
var byteString = BitConverter.ToString(bytes);
string utfString = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
return Ok(new { Posted = true });
}
catch (Exception ex)
{
ex.LogException();
return InternalServerError(ex);
}
}
}
}
以下是我访问过的资源
https://docs.microsoft.com/en-us/previous-versions/aspnet/dn202095(v%3Dvs.118)
https://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/
How To Accept a File POST
感谢任何帮助,谢谢。
试试这个:
[HttpPost]
[Route("api/uploadPDF")]
public async Task<IHttpActionResult> UploadFile()
{
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return StatusCode(HttpStatusCode.UnsupportedMediaType);
}
var fileProvider = await Request.Content.ReadAsMultipartAsync();
var pdfStream = await fileProvider.Contents.First().ReadAsStreamAsync();
//do something with the pdf stream
return Ok(new { Posted = true });
}
catch (Exception ex)
{
ex.LogException();
return InternalServerError(ex);
}
}
我正在尝试使用 Angular 上传 PDF 8. 我正在成功获取用户在前端选择的文件。我正在将一些东西传递给后端,但是当我尝试从内存流中读取文件时,在将其转换为字符串的测试过程中,我得到了“[object FileList]”而不是文件的内容。
这是我不熟悉的swagger吗?我想我可能比以前更困了。
下面是我HTML选择的文件。
<div>
<form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">
<div>
<!-- TODO: rename profile -->
<input type="file" name="profile" (change)="onFileSelect($event)"
accept=".pdf"/>
</div>
<div>
<button type="submit">Upload</button>
</div>
</form>
</div>
下面是我的打字稿:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
@Component({
selector: 'app-pdf',
templateUrl: './pdf.component.html',
styleUrls: ['./pdf.component.css']
})
export class PDFComponent implements OnInit {
SERVER_URL = "http://localhost:64528/api/uploadPDF";
uploadForm: FormGroup;
file;
constructor(private formBuilder: FormBuilder, private httpClient: HttpClient) { }
ngOnInit() {
this.uploadForm = this.formBuilder.group({
profile:['']
});
}
onFileSelect(event){
var file = event.target.files;
if(file.length > 0){
this.file = event.target.files[0];
this.uploadForm.get('profile').setValue(file);
var confirm = this.uploadForm.get('profile').value;
}
}
onSubmit(){
const formData = new FormData();
formData.append('file', this.uploadForm.get('profile').value);
this.httpClient.post<any>(this.SERVER_URL, formData).subscribe(
(res) => console.log(res),
(err) => console.log(err)
);
}
}
下面是我的 C#
using HeadcountTrackingAPI.Repositories;
using HeadcountTrackingAPI.Utilities;
using Swashbuckle.Swagger.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace HeadcountTrackingAPI.Controllers
{
public class PDFController : ApiController
{
// GET api/<controller>
[SwaggerOperation("uploadPDF")]
[HttpPost]
[Route("api/uploadPDF")]
public async Task<IHttpActionResult> UploadFile()
{
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
// Initialize the memorty stream provider
MultipartMemoryStreamProvider memoryStream = new MultipartMemoryStreamProvider();
// Assign it's contents
memoryStream = await Request.Content.ReadAsMultipartAsync();
// Read the contents asynchronosly
using (System.IO.Stream pdfStream = await memoryStream.Contents.First().ReadAsStreamAsync())
{
byte[] bytes = new byte[pdfStream.Length];
// streamBytes to the byte array starting a position 0 and ending at the end of the file
pdfStream.Read(bytes, 0, (int)pdfStream.Length);
var byteString = BitConverter.ToString(bytes);
string utfString = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
return Ok(new { Posted = true });
}
catch (Exception ex)
{
ex.LogException();
return InternalServerError(ex);
}
}
}
}
以下是我访问过的资源 https://docs.microsoft.com/en-us/previous-versions/aspnet/dn202095(v%3Dvs.118)
https://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/
How To Accept a File POST
感谢任何帮助,谢谢。
试试这个:
[HttpPost]
[Route("api/uploadPDF")]
public async Task<IHttpActionResult> UploadFile()
{
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return StatusCode(HttpStatusCode.UnsupportedMediaType);
}
var fileProvider = await Request.Content.ReadAsMultipartAsync();
var pdfStream = await fileProvider.Contents.First().ReadAsStreamAsync();
//do something with the pdf stream
return Ok(new { Posted = true });
}
catch (Exception ex)
{
ex.LogException();
return InternalServerError(ex);
}
}