Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在filestream上设置文件类型_Javascript_C#_Filestream - Fatal编程技术网

Javascript 如何在filestream上设置文件类型

Javascript 如何在filestream上设置文件类型,javascript,c#,filestream,Javascript,C#,Filestream,我正在尝试将文件流从c#发送到我的js后端。名称和路径正确发送,但当我记录进入后端的文件时,类型似乎丢失了,我绝对需要文件类型,但我不知道如何传递它。有人能帮我吗 输入的对象: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 13920, path: '/var/folders/5g/f343vctd6hd7smyd5ybnfp4m000

我正在尝试将文件流从c#发送到我的js后端。名称和路径正确发送,但当我记录进入后端的文件时,类型似乎丢失了,我绝对需要文件类型,但我不知道如何传递它。有人能帮我吗

输入的对象:

File {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 13920,
  path: '/var/folders/5g/f343vctd6hd7smyd5ybnfp4m0000gn/T/upload_4aebdbbee06344e12d8566dd706fd1e6',
  name: 'Invoice19.pdf',
  type: null,
  hash: null,
  lastModifiedDate: 2020-03-17T14:11:04.812Z,
  _writeStream: WriteStream {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: true,
      needDrain: false,
      ending: true,
      ended: true,
      finished: true,
      destroyed: true,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: false,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: true,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: false,
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    path: '/var/folders/5g/f343vctd6hd7smyd5ybnfp4m0000gn/T/upload_4aebdbbee06344e12d8566dd706fd1e6',
    fd: null,
    flags: 'w',
    mode: 438,
    start: undefined,
    autoClose: true,
    pos: undefined,
    bytesWritten: 13920,
    closed: false
  }
}
我的c代码

public IAsyncResult BeginExecute()
{
//设置身份验证
client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“承载人”,承载人);
字符串url=”http://12915520.ngrok.io/api/organisations/“+OrganizationID+”/projects/“+ProjectId+”/process”;
字符串响应=null;
bool successfullrequest=false;
尝试
{
使用(FileStream fs=File.Open(@“C:\Users\X Y\Downloads\Invoice19.pdf”,FileMode.Open,FileAccess.Read))
{
//将内容发送到后端,分析结果
HttpContent=新的StreamContent(fs);
MultipartFormDataContent formdata=新的MultipartFormDataContent();
添加(内容,“文件”,“发票19.pdf”);
var result=client.PostAsync(url,formdata).result;
response=result.Content.ReadAsStringAsync().result;
SuccessfullRequest=result.IsSuccessStatusCode;
}
}
//我绝对希望捕获每个异常并将其传递给工作流
捕获(例外情况除外)
{
ExceptionDispatchInfo.Capture(例如InnerException.Throw();
投掷;
}
//如果后端出现问题,则抛出错误
如果(!SuccessfullRequest)
{
抛出新异常(“上传过程中出错”);
}
UploadResponse r=JsonConvert.DeserializeObject(响应);
WriteLine(“上传响应:+r.ToString());
//肮脏的解决方案:因为我们不知道管道需要多长时间来处理上传,所以我们将轮询结果
//由于这是一个poc,所以这是一个临时解决方案,如果发布了,则需要重写(可能使用Webhook)
//var轮询=真;
//做
//{
//response=client.GetAsync(url+“/”+r.uploadId).Result.Content.ReadAsStringAsync().Result;
//如果(响应!=“空”)
//    {
//轮询=假;
//    }
//}while(投票);
//因为我们知道现在有一个响应,所以实际执行请求
//返回client.GetAsync(url+“/”+r.uploadId);
返回null;
}

我认为您需要更改使用MultipartFormDataContent()的方式

这对我有用

using (var content = new MultipartFormDataContent())
{
    content.Add(new StreamContent(stream)
    {
        Headers =
        {
            ContentLength = stream.Length,
            ContentType = new MediaTypeHeaderValue([your content type])
        }
    }, "[name ex: file]", "[file name ex: file.jpg]");
}

我通过这样做使它工作:

MultipartFormDataContent formdata=new MultipartFormDataContent()
foreach(Files.Get中的var filePath(上下文))
{
//创建文件流内容
FileStream fs=File.Open(filePath,FileMode.Open,FileAccess.Read,FileShare.Read);
HttpContent=新的StreamContent(fs);
字符串名称=GetFileName(文件路径);
添加(“内容类型”,GetFileType(名称));
添加(内容,“文件”,名称);
}
//将内容发送到后端并分析结果
var resultPost=client.PostAsync(url,formdata).Result;
response=resultPost.Content.ReadAsStringAsync().Result;
SuccessfullRequest=resultPost.IsSuccessStatusCode;
基本上,我将内部内容的内容类型设置为任何文件类型,然后将外部内容的内容类型设置为多部分/表单数据(通过将其添加到
MultiPartFormData

由于我只支持有限数量的文件类型,因此我能够编写一个简单的函数:

私有字符串GetFileType(字符串名称)
{
char[]charSeparators=新的char[]{.'.};
var splitName=name.Split(字符分隔符);
字符串扩展名=splitName[1].ToLower();
交换机(分机)
{
案例“pdf”:
返回“application/pdf”;
案例“png”:
返回“image/png”;
案例“doc”:
返回“application/msword”;
案例“docx”:
返回“application/vnd.openxmlformatsofcedocument.wordprocessingml.document”;
案例“txt”:
返回“文本/纯文本”;
案例“tif”:
返回“图像/tif”;
案例“jpg”:
返回“image/jpg”;
案例“rtf”:
返回“应用程序/rtf”;
//默认==不支持类型,我们不设置内容类型
违约:
返回“”;
}
}