c# - Upload a File from HTML form using PostAsync -
i want upload file server using webapi. want call webapi in mvc homecontroller. when use webapi directly uploads files when want call webapi within controller using postasync, not send file api reason.
this action in mvc controller:
public async task<actionresult> upload(httppostedfilebase upload) { viewbag.title = "upload files"; if (upload != null && upload.contentlength > 0) { var client = new httpclient(); string fullurl = request.url.scheme + system.uri.schemedelimiter + request.url.host + ":" + request.url.port + "/api/values"; stringcontent httpcontent = new stringcontent(upload.filename); var response = await client.postasync(fullurl, httpcontent); var result = await response.content.readasasync<httpresponsemessage>(); } return view(); }
this .cshtml file:
<form name="form1" method="post" action="/home/upload" enctype="multipart/form-data"> <div> <label for="upload">choose file</label> <input name="upload" type="file" /> </div> <div> <input type="submit" value="submit" /> </div>
finally webapi controller:
[httppost] public httpresponsemessage postfile() { httpresponsemessage result = null; var httprequest = httpcontext.current.request; if (httprequest.files.count > 0) { foreach (string file in httprequest.files) { var postedfile = httprequest.files[file]; var filepath = httpcontext.current.server.mappath("~/files/" + postedfile.filename); postedfile.saveas(filepath); } result = request.createresponse(httpstatuscode.created); } else { result = request.createresponse(httpstatuscode.badrequest); } return result; }
when content post form, it's setup multipart/form-data content type request. can try setup request content type multipart/form-data explicitly.
var requestcontent = new multipartformdatacontent(); var filecontent = new streamcontent(upload.inputstream); filecontent.headers.contenttype = upload.contenttype; requestcontent.add(filecontent, upload.filename, upload.filename); client.postasync(url, requestcontent);
Comments
Post a Comment