in mvc , use httppostedfilebase
file form (multipart/form-data
) :
view :
<form role="form" enctype="multipart/form-data"> <input type="text" name="productcode"/> <input type="text" name="productcat"/> <input type="text" name="price"/> <input type="text" name="file" multiple/> </form>
model :
public class product { public int productid{ set; get; } public string productcode { set; get; } public int productcat { set; get; } public decimal price { set; get; } } public class productdata { public product pro { set; get; } public list<httppostedfilebase> file { set; get; } }
action :
public actionresult postproduct(product prop,list<httppostedfilebase> file) { productdata data = new productdata(); data.pro=prop; data.file=file; client.baseaddress = new uri("http://localhost/99"); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json")); httpresponsemessage res = client.postasjsonasync("/api/product/postproduct",data).result; // in here , error :"error getting value 'readtimeout' on 'system.web.httpinputstream'",and cannot post data web api if (res.issuccessstatuscode) { return partialview("_success"); } else return partialview("_error"); }
in web api :
[route("postproduct")] [responsetype(typeof(product))] public ihttpactionresult postproduct(productdata prod) { .... }
i don't know how post data (model,file) mvc web api?
it involves bit of ceremony.
this article should take care of basics of uploading file form parameters http://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2.
for clarity, example article:
public async task<httpresponsemessage> postformdata() { // check if request contains multipart/form-data. if (!request.content.ismimemultipartcontent()) { throw new httpresponseexception(httpstatuscode.unsupportedmediatype); } string root = httpcontext.current.server.mappath("~/app_data"); var provider = new multipartformdatastreamprovider(root); try { // read form data. await request.content.readasmultipartasync(provider); // illustrates how file names. foreach (multipartfiledata file in provider.filedata) { trace.writeline(file.headers.contentdisposition.filename); trace.writeline("server file path: " + file.localfilename); } // show key-value pairs. foreach (var key in provider.formdata.allkeys) { foreach (var val in provider.formdata.getvalues(key)) { trace.writeline(string.format("{0}: {1}", key, val)); } } return request.createresponse(httpstatuscode.ok); } catch (system.exception e) { return request.createerrorresponse(httpstatuscode.internalservererror, e); } }
Comments
Post a Comment