java:
File file = new File("F:\\tmp\\taiping\\conf-1.json")
MultipartEntity mpEntity = new MultipartEntity()// 文件传输
ContentBody cbFile = new FileBody(file)
mpEntity.addPart("fileContent", cbFile)
CloseableHttpClient client = HttpClients.createDefault()
HttpPost post = new HttpPost("http://localhost:9999/api/values")
post.setEntity(mpEntity)
try {
CloseableHttpResponse response = client.execute(post)
String result = IOUtils.toString(response.getEntity().getContent())
System.out.println(result)
} catch (Exception e) {
e.printStackTrace()
}
.net http webapi
public HttpResponseMessage Post()
{
var content = Request.Content
var uploadDir = HttpContext.Current.Server.MapPath("~/Upload")
var newFileName = ""
var sp = new MultipartMemoryStreamProvider()
Task.Run(async () =>await Request.Content.ReadAsMultipartAsync(sp)).Wait()
foreach (var item in sp.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "")
newFileName = uploadDir + "\\" + filename
var ms = item.ReadAsStreamAsync().Result
using (var br = new BinaryReader(ms))
{
var data = br.ReadBytes((int)ms.Length)
File.WriteAllBytes(newFileName, data)
}
}
}
var result = new Dictionary<string, string>()
result.Add("result", newFileName)
var resp = Request.CreateResponse(HttpStatusCode.OK, result)
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain")
return resp
}
WebApi编译后,其实就是一个dll文件,并不是一个可执行文件,所以它需要一个宿主.我所知道的,webapi一共有三种宿主:
1. IIS
2. SelfHost
3. OwinSelfHost
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)