SpringMVC uploads images and springmvc uploads files

Source: Internet
Author: User

SpringMVC uploads images and springmvc uploads files

I. Put forward the Image Upload Method

Public class UpPicture {

Public static void upPicture (MultipartFile fl, HttpServletRequest req) throws Exception {

String path = req. getSession (). getServletContext (). getRealPath ("/") + "upload /";
// Real path
String fileName = fl. getOriginalFilename ();
File targetFile = new File (path, fileName );
If (! TargetFile. exists ()){
TargetFile. mkdirs ();
}
System. out. println (path );
// Save
Try {
Fl. transferTo (targetFile );
} Catch (Exception e ){
E. printStackTrace ();
}
}
/**
* Determine the file size
* @ Param fl
* @ Return
*/
Public static Boolean size (MultipartFile fl ){
// System. out. println (fl. length ());
// Determine the file size
Long s = fl. getSize ();
If (s> = 2000000000 ){
Return false;
}
Return true;
}
/**
* Determine the image format
* @ Param flFileName
* @ Return
*/
Public static Boolean geShi (String flFileName ){
// Determine whether the input image is an image
Set <String> set = UpPicture. imgSet ();
Boolean B = false;
For (String s: set ){
If (flFileName. substring (flFileName. length ()-3). inclusignorecase (String) s )){
B = true;
Break;
}
}
Return B;
}
/**
* Put common image formats in set
*
* @ Return
*/
Public static Set imgSet () {// BMP, JPG, JPEG, PNG, and GIF.
Set <String> set = new HashSet <> ();
Set. add ("bmp ");
Set. add ("jpg ");
Set. add ("jpeg ");
Set. add ("png ");
Set. add ("gif ");
Return set;
}
}
Ii. controller Layer
/**
* Update the Avatar page
* @ Return
*/
@ RequestMapping ("/do_editphoto.do ")
@ ResponseBody
Public String doModiPhoto (Integer noid, MultipartFile file, HttpServletRequest request, Model model ){
Noid = 1;
String fileFileName = file. getOriginalFilename ();
Boolean B = UpPicture. size (file );
If (! B ){
Return "invalid format ";
}
B = UpPicture. geShi (fileFileName );
If (! B ){
Return "invalid format ";
}
Try {
UpPicture. upPicture (file, request );
} Catch (Exception e ){
Return "error ";
}
// The save path is
String path = "/family/upload/" + fileFileName;
UserService. updatPhotoUrl (path, noid );
Return path;
}
/**
* Upload images by cropping Images
* @ Param x
* @ Param y
* @ Param w
* @ Param h
* @ Param fl
* @ Param session
* @ Return
*/
@ RequestMapping ("do_crop ")
@ ResponseBody
Public String do_crop (String flName, String flFileName, Integer x, Integer y, Integer w, Integer h, HttpSession session ){
If (x = null | y = null | w = null | h = null ){
Return "Please try again later ";
}
Try {
ImageCut. cutImage (flFileName, x, y, w, h );
} Catch (Exception e ){
Return "the system is not stable ";
}
// Obtain the session
Integer userId = (Integer) session. getAttribute ("userId ");
UserId = 1;
// The save path is
String path = flName;
UserService. updatPhotoUrl (path, userId );
Return "OK ";
}

Iii. jsp page

<Div id = "firstDiv">
<Form id = "formImg">
<Div>
<Input type = "hidden" name = "noid" value = "$ {noid}">
<Span> change profile picture: </span> <br>
<Input type = "file" name = "file" id = "file"> <br>
<A id = "qclose" href = "javascript: void (0)"> display cropping preview </a>
</Div> <br>
<! -- Crop an image -->
<Div id = "qietu">

<Div id = "preview-pane">
<Div class = "preview-container">

</Div>
</Div>
</Div>
</Form> <br>
<Div>
<Form id = "crop_form">
<Input type = "hidden" name = "flName" value = "$ {photo}"/>
<Input type = "hidden" name = "flFileName" value = "D:/tomcat8/tomcat8/webapps/$ {photo}"/>
<Input type = "hidden" id = "x" name = "x"/>
<Input type = "hidden" id = "y" name = "y"/>
<Input type = "hidden" id = "w" name = "w"/>
<Input type = "hidden" id = "h" name = "h"/>
<Button type = "button" id = "crop_submit" class = "btn-info" onclick = "ajax_crop ()"> confirm cropping and save </button>
</Form>
</Div>
</Div>
</BODY>
<Script type = "text/javascript">

// Cut the image for upload
Function ajax_crop (){
Var url = "$ {BasePath}/user/do_crop.do ";

$ ("# Crop_form"). ajaxSubmit ({
Type: 'post ',
Url: url,
ClearForm: true, // clear the values of all form elements
ResetForm: true, // reset the values of all form elements
Success: function (STR ){
If (STR = "OK "){
Alert ("modified successfully ");
Window. location. reload ();
} Else {
Alert ("modification failed ");
}
},
Error: function (XmlHttpRequest, textStatus, errorThrown ){
Alert ("Upload Failed ");
}
});
}
$ ("# Qclose"). click (function (){
$ ("# Preview-pane"). show ();
})
// Upload an image
$ ("# File"). change (function (){
Var url = "$ {BasePath}/user/do_editphoto.do ";
Var files = $ ("# file"). val ();
If (files = null | files = ""){
Alert ("cannot be blank ");
Return;
}
$ ("# FormImg"). ajaxSubmit ({
Type: "post ",
Url: url,
Success: function (str ){
If (str = "error "){
Alert ("Please try again later ");
} Else if (str = "The format is incorrect "){
Alert ("Incorrect format ");
} Else {
Window. location. reload ();
}
},
Error: function (XmlHttpRequest, textStatus, errorThrown ){
Alert ("Edit failed ");
}
})

})

JQuery (function ($ ){
// Create variables (in this scope) to hold the API and image size
Var jcrop_api,
Boundx,
Boundy,
// Grab some information about the preview pane
$ Preview = $ ('# preview-pane '),
$ Pcnt = $ ('# preview-pane. preview-iner '),
$ Pimg = $ ('# preview-pane. preview-container img '),
Xsize = $ pcnt. width (),
Ysize = $ pcnt. height ();
Console. log ('init ', [xsize, ysize]);
$ ('# Hahhah'). Jcrop ({
OnChange: updatePreview,
OnSelect: updatePreview,
AspectRatio: 1,
// AspectRatio: xsize/ysize,
OnRelease: clearCoords
}, Function (){
// Use the API to get the real image size
Var bounds = this. getBounds ();
Boundx = bounds [0];
Boundy = bounds [1];
// Store the API in the jcrop_api variable
Jcrop_api = this;
// Move the preview into the jcrop container for css positioning
$ Preview. appendTo (jcrop_api.ui.holder );
});



Function updatePreview (c ){

If (parseInt (c. w)> 0 ){
Var rx = xsize/c. w;
Var ry = ysize/c. h;
$Pimg.css ({
Width: Math. round (rx * boundx) + 'px ',
Height: Math. round (ry * boundy) + 'px ',
MarginLeft: '-' + Math. round (rx * c. x) + 'px ',
MarginTop: '-' + Math. round (ry * c. y) + 'px'
});
}
Console. log ([c. x, c. y, c. w, c. h]);
$ ("# X"). val (c. x );
$ ("# Y"). val (c. y );
$ ("# W"). val (c. w );
$ ("# H"). val (c. h );
};
Function clearCoords (){
$ ('# Coords input'). val ('');
};
});
</Script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.