spring 3 upload many files - spring-mvc

yeah,our customer want to upload more than one file.
we use spring 3 mvc.
the official example like this:
markup:
<form method="post" action="/form" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
code:
#RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
there is only one file,so i can write the file input name in the method.
but what should i do if i want to upload many files.
i could not write all the file input names because if is generated by the js code.
i only know that its name like 'attach_'
then ,what should i write in the method ? if i write like this
#RequestParam() MultipartFile file
or
#RequestParam("attach_") MultipartFile file
i'll get a error.

A much simpler way - works for me
/*** Upload Images ***/
#RequestMapping(value = "/images/upload", method = RequestMethod.POST)
public void upload(#RequestParam("file") List<MultipartFile> files, #RequestParam("user") String user) {
files.forEach((file -> System.out.println(file.getOriginalFilename())));
}

I have it working with Spring 3.0.4 (there was an issue in previous versions of Spring, so be sure to use >= 3.0.4).
To test it, you can use the following steps:
public class MultiPartFileUploadBean {
private List<MultipartFile> files;
public void setFiles(List<MultipartFile> files) {
this.files = files;
}
public List<MultipartFile> getFiles() {
return files;
}
}
The controller:
#RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
public String uploadtestProcess(MultiPartFileUploadBean file, BindingResult bindingResult,
Model model) throws IOException {
... // binding check
StringBuilder sb = new StringBuilder();
List<MultipartFile> files = file.getFiles();
for(MultipartFile f:files)
sb.append(String.format("File: %s, contains: %s<br/>\n",f.getOriginalFilename(),new String(f.getBytes())));
String content = sb.toString();
model.addAttribute("content", content);
return "uploadtest";
}
The jsp:
<form method="post" action="/uploadtest" enctype="multipart/form-data">
<p>Type: <input type="text" name="type" value="multiPartFileSingle" size="60" /></p>
<p>File 1: <input type="file" name="files[0]" size="60" /></p>
<p>File 2: <input type="file" name="files[1]" size="60" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
<c:if test="${not empty content}">
<p>The content uploaded: <br/>${content}</p>

I found clearer to use the MultipartHttpServletRequest object as a parameter to the controller method:
#RequestMapping(value = "/save", method=RequestMethod.POST)
protected String save(Model model, MultipartHttpServletRequest multipartRequest) {
MultipartFile file = multipartRequest.getFile("field-name");
// Also multiple files with same name
List<MultipartFile> files = multipartRequest.getFiles("multifield-name");
// ...
}
Link to the docs: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-multipart-resolver-commons

You use model and form.
( Html / Jsp )
<form id="uploadForm" method="POST"enctype="multipart/form-data/charset=UTF-8">
//...multi file, add dynamic input
<input type="file" name="file"/>
<input type="file" name="file"/>
<input type="file" name="file"/>
<input type="file" name="file"/>
</form>
<input type="button" id="save_button" value="save" />
(Js)
var form = new FormData(document
.getElementById('uploadForm'));
$.ajax({
url : "/test/upload/file,
type : 'POST',
dataType : 'text',
data : form,
processData : false,
contentType : false,
success : function(response) {
if (response == "success") {
document.location.reload(true);
} else {
$("#editMsg").text("fail");
}
},
error : function(request, status, error) {
}
});
( Model )
public class fileModel {
private List<MultipartFile> file; // this name = input name
... setter, getter
}
( Controller )
#RequestMapping(value = "/upload/file", method = RequestMethod.POST)
public #ResponseBody String uploadFiles(fileModel model, HttpServletRequest req) {
return "success" // <-- debug. break point !! Your watch model.
}

You can find it here:
http://dhruba.name/2008/12/27/implementing-single-and-multiple-file-multipart-uploads-using-spring-25/

Related

Unable to save my image in a folder using ASP.NET MVC

I have tried this code but I'm unable to save the image/file in the specified folder. What is wrong with the code?
Controller:
public ActionResult Work(Work workmodel, HttpPostedFileBase workpostpath)
{
if (workpostpath != null)
{
// Upload your service images
using (entities = new saabinteriormodel())
{
string workpic = System.IO.Path.GetFileName(workpostpath.FileName);
string workpath = System.IO.Path.Combine(Server.MapPath("~/Content/Images/work/"), workpic);
workpostpath.SaveAs(workpath);
Work work = new Work
{
work_image = "~/Content/Images/work/" + workpic};
workmodel.work_image = work.work_image;
entities.Works.Add(work);
entities.SaveChanges();
}
}
return View();
}
}
View:
#using (Html.BeginForm ("Work", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<input id="uploadimage" type="file" />
#ViewBag.Message
<input id="work" type="submit" value="Save Work"/>
}
Thank you.
you're creating a new record in db, but not saving posted files anywhere. try
workpostpath.SaveAs(Server.MapPath("~/folder/file.extension"));
Alsou you could retrieve the posted files from request
HttpPostedFileBase file = Request.Files[0];

How can I download a PDF file from a path or folder using asp.net

Good afternoon, I have an asp.net project and I would like that through an asp.net c # form a patient can download a certificate from a path or folder through their identification number or code, the folder it contains contains pdf and are organized by ID number
Thank you
Due to your vague description, I am not sure if you are an mvc project
or a core project.
The following is a case of downloading pdf in each project, please refer to:
In mvc:
public ActionResult DownLoad()
{
return View();
}
[HttpPost]
public ActionResult DownLoad(string id)
{
//PdfFiles is the name of the folder where these pdf files are located
var path = Server.MapPath("~/PdfFiles/pdf" + id + ".pdf");
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "application/pdf", Path.GetFileName(path));
}
View:
<form method="post" action="DownLoad">
Pdf Id: <input id="Text1" type="text" name="id" />
<input id="Submit1" type="submit" value="submit" />
</form>
Here is the test result:
In Core:
public IActionResult DownLoad()
{
return View();
}
[HttpPost]
public async Task<IActionResult> DownLoad(string id)
{
//here i put the PdfFiles folder in the wwwroot folder
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot", "PdfFiles/pdf" + id + ".pdf");
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "application/pdf", Path.GetFileName(path));
}
View:
<form asp-action="DownLoad" method="post">
Pdf Id: <input id="Text1" type="text" name="id"/>
<input id="Submit1" type="submit" value="submit" />
</form>
Here is the test result:

InvalidCastexception upload multiple images

Hi everyone I am creating an application using MVC 5, with a code first database,The code below shows the code I am currently trying to use to upload multiple images but I get an InvalidCastexception when trying to cast 'System.String' to type 'System.Web.HttpPostedFileBase'.
Thanks for your time and any help with this issue is greatly appreciated.
Images Controller
// GET: Images/Upload
[HttpGet]
public ActionResult Upload()
{
return View();
}
// POST: Images/Upload
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
{
HttpFileCollectionBase files = Request.Files;
foreach (HttpPostedFileBase file in files)
{
int length = file.ContentLength;
string type = file.ContentType;
string filename = file.FileName;
}
return RedirectToAction("Upload");
}
upload view
#{Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Upload</title>
</head>
<body>
<form method="post" action="~/Images/Upload" id="form1" enctype="multipart/form-data">
#if (ViewData.Model != null)
{
foreach (var item in ViewData.Model)
{
<img src="/Images/#item["Path"]" alt="FileUpload Image" />
}
}
<input type="file" name="uploadFiles" id="FileUpload" multiple="multiple" />
<input type="submit" name="btnSubmit" value="Upload" id="btnSubmit" />
</form>
</body>
</html>
You can't do that
foreach (HttpPostedFileBase file in files)
because the enumerator of HttpFileCollection will return names of the files (string) but not HttpPostedFileBase so you will got InvalidCastexception
Use uploadFiles in the loop instead of HttpFileCollectionBase
public ActionResult Upload(IEnumerable<HttpPostedFileBase> uploadFiles)
{
foreach (var file in uploadFiles)
{
int length = file.ContentLength;
string type = file.ContentType;
string filename = file.FileName;
}
return RedirectToAction("Upload");
}
or use for and index:
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
int length = files[i].ContentLength;
string type = files[i].ContentType;
string filename = files[i].FileName;
}

How to show image from H2 database to Thymeleaf?

I'm doing spring boot, using H2 database, thymeleaf view.
I have a form to upload image to save into H2 database(byte[] image),
In thymeleaf, how to show image? anyone tell me the solution?
controller:
#RequestMapping(value = "user/new", method = RequestMethod.GET)
public String newBeans(Model model) {
model.addAttribute("usersss", new Beans());
return "userform";
}
#RequestMapping(value = "user", method = RequestMethod.POST)
public String saveUser(Beans beans) {
RepositoryUser.save(beans);
return "redirect:/users";
}
form:
<form>
<label>Avatar:</label>
<input type="file" th:field="${usersss.Avatar}"/>
<button type="submit">Submit</button>
</form>
shows:
<form>
<label>Avatar:</label>
<p>
?????????
</p>
</form>
Although there are many different ways to do this,here is some sample code which you can use for the same :
#RequestMapping(value = "/user/avatar/{userId}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<InputStreamResource> downloadUserAvatarImage(#PathVariable Long userId) {
UserObject userAvatar = RepositoryUser.findUserAccountAvatarById(userId);//Could be a handle to a file stream as well,which could be incorporated accordingly
return ResponseEntity.ok()
.headers("Content-Disposition", "inline;filename=\""
+ userAvatar.getUserName() + "\"")
.contentLength(userAvatar.getImageBlob().getLength())
.contentType(MediaType.parseMediaType(userAvatar.getImageBlob().getContentType()))
.body(new InputStreamResource(userAvatar.getImageBlob().getBinaryStream()));
}
And then in your thymeleaf :
<form>
<label >Avatar :</label>
<p>
<img class="picture" th:src="#{'/user/avatar/'+${userId}}" />
</p>
</form>
Hope this helps.

How to upload file with web-api

Client side code:
<form action="api/MyAPI" method="post" enctype="multipart/form-data">
<label for="somefile">File</label> <input name="somefile" type="file" />
<input type="submit" value="Submit" />
</form>
And how to process upload file with mvc web-api,have some sample code?
HTML Code:
<form action="api/MyAPI" method="post" enctype="multipart/form-data">
<label for="somefile">File</label>
<input name="somefile" type="file" />
<input type="submit" value="Submit" />
</form>
Controller
// POST api/MyAPI
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.AllKeys[0] == "image")
{
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
try below link
this link use for me hopefully it will work you
http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
You can use ApiMultipartFormFormmatter to upload file to web api 2.
By using this library, you can define a view model to get parameters submitted from client-side. Such as:
public class UploadFileViewModel
{
public HttpFile Somefile{get;set;}
}
And use it in your Api controller like this:
public IHttpActionResult Upload(UploadFileViewModel info)
{
if (info == null)
{
info = new UploadFileViewModel();
Validate(info);
}
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok();
}
Nested objects can be parsed by this library.

Resources